Foss Lab Manual
Foss Lab Manual
LAB MANUAL
B.TECH
II YEAR – II SEM (R20)
(2022-23)
Prepared By
Dr. Ch V Raghavendran
Professor
LIST OF EXPERIMENTS
1. Session-1
a) Log into the system
b) Use vi editor to create a file called myfile.txt which contains some text.
c) correct typing errors during creation.
d) Save the file
e) logout of the system
Session-2
a) Log into the system
b) open the file created in session 1
c) Add some text
d) Change some text
e) Delete some text
f) Save the Changes
g) Logout of the system
2. a) Log into the system
b) Use the cat command to create a file containing the following data. Call it mytable use tabs to
separate the fields.
1425 Ravi 15.65
4320 Ramu 26.27
6830 Sita 36.15
1450 Raju 21.86
c) Use the cat command to display the file, mytable
d) Use the vi command to correct any errors in the file, mytable.
e) Use the sort command to sort the file my table according to the first field. Call the sorted file
my table (same name)
f) Print the file my table
g) Use the cut and paste commands to swap fields 2 and 3 of my table. Call it my table (same
name)
h) Print the new file, mytable
i) Logout of the system.
3. A)
a) Login to the system
b) Use the appropriate command to determine your login shell
c) Use the /etc/passwd file to verify the result of step b.
d) Use the who command and redirect the result to a file called myfile1. Use the more command
to see the contents of myfile1.
e) Use the date and who commands in sequence (in one line) such that the output of date will
display on the screen and the output of who will be redirected to a file called myfile2.
Use the more command to check the contents of myfile2.
B) Write a sed command that deletes the first character in each line in a file.
b) Write a sed command that deletes the character before the last character in each line in a file.
c) Write a sed command that swaps the first and second words in each line in a file.
4. a) Pipe your /etc/passwd file to awk, and print out the home directory of each user.
b) Develop an interactive grep script that asks for a word and a file name and then tells how many
lines contain that word.
c) Repeat
d) Part using awk
5. a)Write a shell script that takes a command –line argument and reports on whether it is directory,
a file, or something else
b) Write a shell script that accepts one or more file name as arguments and converts all of them to
uppercase, provided they exist in the current directory.
c) Write a shell script that determines the period for which a specified user is working on the
system.
6. a)Write a shell script that accepts a file name starting and ending line numbers as arguments and
displays all the lines between the given line numbers.
b) Write a shell script that deletes all lines containing a specified word in one or more files supplied
as arguments to it.
7. a)Write a shell script that computes the gross salary of a employee according to the following
rules:
i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
The basic salary is entered interactively through the key board.
b) Write a shell script that accepts two integers as its arguments and computers the value of first
number raised to the power of the second number.
8. a)Write an interactive file-handling shell program. Let it offer the user the choice of copying,
removing, renaming, or linking files. Once the user has made a choice, have the program ask the
user for the necessary information, such as the file name, new name and so on.
b) Write shell script that takes a login name as command – line argument and reports when that
person logs in
c) Write a shell script which receives two file names as arguments. It should check whether the
two file contents are same or not. If they are same then second file should be deleted.
9. a)Write a shell script that displays a list of all the files in the current directory to which the user
has read, write and execute permissions.
b) Develop an interactive script that ask for a word and a file name and then tells how many times
that word occurred in the file.
c) Write a shell script to perform the following string operations:
i) To extract a sub-string from a given string.
ii) To find the length of a given string.
10 .Write a C program that takes one or more file or directory names as command line input and
reports the following information on the file:
i) File type ii)Number of links iii)Read, write and execute permissions
iv) Time of last access
(Note : Use stat/fstat system calls)
11. Write C programs that simulate the following unix commands:
a)mv b)cp (Use system calls)
12. Write a C program that simulates ls Command (Use system calls / directory API)
13. Write a shell script to accept the name of the file from standard input and perform the
following tests on it a) File executable b) File readable c) File writable d) Both readable & writable
14. Write an awk program to print sum, avg of students marks list
15. Write an awk program which will find maximum word and its length in the given input file
Course Blooms
S.No Course Outcomes
Code - CO Taxonomy
Demonstrate UNIX commands for file handling and
1 CO1 Application
process control
Course Course
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
Code Outcomes
Demonstrate
UNIX commands
CO1 for file handling 1 2 1 2 1
and process
control
Construct regular
expressions for
pattern matching
CO2 2 2 2 2 2 2
and apply them to
various filters for
a specific task.
Analyze a given
problem and
apply requisite
facets of shell
CO3 2 3 3 2 2 2 2
programming in
order to devise a
shell script to
solve the problem
Apply C language
CO4 to simulate UNIX 2 2 3 3 2 1
commands
Apply UNIX
CO5 library functions 2 3 3 3 1 1 2
and system calls.
Develop
CO6 programs using 1 3 3 3 2 2 2
AWK concepts.
GENERAL INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
o Laboratory observation notes.
o Laboratory Record updated up to the last session experiments.
o Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note
book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high-end branded systems, which should
be utilized properly.
8. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe
punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept
properly.
INDEX
CO PAGE
S.NO NAME OF THE EXPERIMENT
LEVEL NO
1. Session-1
a) Log into the system
b) Use vi editor to create a file called myfile.txt which contains
some text.
c) Correct typing errors during creation.
d) Save the file
e) logout of the system
2 Session-2 CO1 8-9
a) Log into the system
b) open the file created in session 1
c) Add some text
d) Change some text
e) Delete some text
f) Save the Changes
g) Logout of the system
a) Log into the system
b) Use the cat command to create a file containing the following
data. Call it mytable use tabs to separate the fields.
1425 Ravi 15.65
4320 Ramu 26.27
6830 Sita 36.15
1450 Raju 21.86
c) Use the cat command to display the file, mytable
3 CO1 10-12
d) Use the vi command to correct any errors in the file, mytable.
e) Use the sort command to sort the file my table according to
the first field. Call the sorted file my table (same name)
f) Print the file my table
g) Use the cut and paste commands to swap fields 2 and 3 of my
table. Call it my table (same name)
h) Print the new file, mytable
i) Logout of the system.
A)
a) Login to the system
4 CO2 13
b) Use the appropriate command to determine your login shell
c) Use the /etc/passwd file to verify the result of step b.
d) Use the who command and redirect the result to a file called
myfile1. Use the more command to see the contents of myfile1.
e) Use the date and who commands in sequence (in one line)
such that the output of date will display on the screen and the
output of who will be redirected to a file called myfile2.
Use the more command to check the contents of myfile2.
B) Write a sed command that deletes the first character in each
line in a file.
b) Write a sed command that deletes the character before the last
character in each line in a file.
c) Write a sed command that swaps the first and second words
in each line in a file.
a) Pipe your /etc/passwd file to awk, and print out the home
directory of each user.
b) Develop an interactive grep script that asks for a word and a
5 CO6 14-15
file name and then tells how many lines contain that word.
c) Repeat
d) Part using awk
a)Write a shell script that takes a command –line argument and
reports on whether it is directory, a file, or something else
b) Write a shell script that accepts one or more file name as
6 arguments and converts all of them to uppercase, provided they CO3 16-19
exist in the current directory.
c) Write a shell script that determines the period for which a
specified user is working on the system.
a)Write a shell script that accepts a file name starting and ending
line numbers as arguments and displays all the lines between the
7 given line numbers. CO3 20-21
b) Write a shell script that deletes all lines containing a specified
word in one or more files supplied as arguments to it.
a)Write a shell script that computes the gross salary of a
employee according to the following rules:
i) If basic salary is < 1500 then HRA =10% of the basic and DA
=90% of the basic.
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of
8 CO3 22-23
the basic
The basic salary is entered interactively through the key board.
b) Write a shell script that accepts two integers as its arguments
and computers the value of first number raised to the power of
the second number.
a) Write an interactive file-handling shell program. Let it offer
the user the choice of copying, removing, renaming, or linking
9 files. Once the user has made a choice, have the program ask the CO3 24-26
user for the necessary information, such as the file name, new
name and so on.
ADDITIONAL EXPERIMENTS
Write a shell script that deletes all lines containing the specified
1 CO3 37-38
word in one or more files Supplied as arguments to it.
2 Write a shell script to find factorial of a given number. CO3 39
Introduction to UNIX
UNIX is an operating system which was first developed in the 1960s by a group of AT&T
employees Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna at Bell Labs, and
has been under constant development ever since. By operating system, we mean the suite of
programs which make the computer work. It is a stable, multi-user, multi-tasking system for
servers, desktops and laptops.
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows
which provides an easy to use environment. However, knowledge of UNIX is required for
operations which aren’t covered by a graphical program, or for when there is no windows interface
available, for example, in a telnet session.
There are many different versions of UNIX, although they share common similarities. The
most popular varieties of UNIX are Sun Solaris, GNU, and MacOS X. Linux is also a flavor of
UNIX which is freely available.
Several people can use a UNIX computer at the same time; hence UNIX is called a
multiuser system. A user can also run multiple programs at the same time; hence UNIX is a
multitasking environment.
UNIX Architecture
Here is a basic block diagram of a UNIX system −
The main concept that unites all the versions of Unix is the following four basics −
Kernel − The kernel is the heart of the operating system. It interacts with the hardware and most
of the tasks like memory management, task scheduling and file management.
Shell − The shell is the utility that processes your requests. When you type in a command at your
terminal, the shell interprets the command and calls the program that you want. The shell uses
standard syntax for all commands. C Shell, Bourne Shell and Korn Shell are the most famous
shells which are available with most of the UNIX variants.
Commands and Utilities − There are various commands and utilities which you can make use of
in your day to day activities. cp, mv, cat and grep, etc. are few examples of commands and utilities.
There are over 250 standard commands plus numerous others provided through 3rd party software.
All the commands come along with various options.
Files and Directories − All the data of UNIX is organized into files. All files are then organized
into directories. These directories are further organized into a tree-like structure called the file
system.
All the files are grouped together in the directory structure. The file-system is arranged in
a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root
(written as a slash / ).
In the diagram above, we see that the home directory of the undergraduate student “ee51vn”
contains two sub-directories (docs and pics) and a file called report.doc.
The full path to the file report.doc is “/home/its/ug1/ee51vn/report.doc”
1) cal:
Displays the calendar of the current month.
At the terminal write the following:
[user1@com]$ cal
[user1@com]$ cal -m
[user1@com]$ cal -j
[user1@com]$ cal –y
2) clear:
This command clears the screen.
At the terminal write the following:
[user1@com]$ clear
3) who:
This command reveals the user who is currently logged in.
At the terminal write the following:
[user1@com]$ who
[user1@com]$ who -q
[user1@com]$ who -H
[user1@com]$ who –m
4) date:
Displays current time and date.
At the terminal write the following:
[user1@com]$ date
[user1@com]$ date –d “2 days ago”
[user1@com]$ date +%D
[user1@com]$ date +%d
[user1@com]$ date +%d%m%h
5) mkdir:
To create a directory, the ‘mkdir’ command is used.
At the terminal write the following:
[user1@com]$ cd acet/
[user1@com]$ ls
[user1@com]$ cd newfiles/
[user1@com]$ ls
[user1@com]$ mkdir newfile1
[user1@com]$ ls
6) cat
Cat allows you to read multiple files and then print them out. You can combine files by using the
> operator and append files by using >>.
Syntax: cat [argument] [specific file]
Example:
cat a1.txt
If you want to append three files (a1.txt, a2.txt, a3.txt), give the command as,
cat a1.txt a2.txt a3.txt > all
7) cd / chdir
cd (or chdir) stands for “change directory”. This command is the key command to move around
your file structure.
Syntax: cd [name of directory you want to move to]
When changing directories, start with / and then type the complete file path, like
cd /dir1/sdir1
8) cp
The cp command copies files or directories from one place to another. You can copy a set of files
to another file, or copy one or more files under the same name in a directory. If the destination of
the file you want to copy is an existing file, then the existing file is overwritten. If the destination
is an existing directory, then the file is copied into that directory.
Syntax: cp [options] file1 file2
If you want to copy the file courses.php into the directory called acet, you give the command as:
cp courses.php/acet/
A handy option to use with cp is -r. This recursively copies a particular directory and all of its
contents to the specified directory, so you won’t have to copy one file at a time.
9) grep
The grep command searches a file or files for lines that match a provided regular expression.
“grep” comes from a command meaning to globally search for a regular expression and then print
the found matches.
Syntax: grep [options] regular expression [files]
To exit this command, type 0 if lines have matched, 1 if no lines match, and 2 for errors. This is
very useful if you need to match things in several files. If you wanted to find out which files in our
acet directory contained the word “B.Tech(IT)” you could use grep to search the directory and
match those files with that word. All that you have to do is give the command as shown:
grep ‘B.Tech(IT)’ /acet/*
The * used in this example is called a meta-character, and it represents matching zero or more of
the preceding characters. In this example, it is used to mean “all files and directories in this
directory”. So, grep will search all the files and directories in acet and tell you which files contain
“B.Tech(IT)”.
10) ls
ls will list all the files in the current directory. If one or more files are given, ls will display the
files contained within “name” or list all the files with the same name as “name”. The files can be
displayed in a variety of formats using various options.
Syntax: ls [options] [names]
ls command stands for list. If you are in a directory and you want to know what files and directories
are inside that directory, type ls. Sometimes the list of files is very long and it flies past your screen
so quickly you miss the file you want. To overcome this problem give the command as shown
below:
ls | more
The character | (called pipe) is typed by using shift and the \ key. | more will show as many files
as will fit on your screen, and then display a highlighted “more” at the bottom. If you want to see
the next screen, hit enter (for moving one line at a time) or the spacebar (to move a screen at a
time). | more can be used anytime you wish to view the output of a command in this way.
A useful option to use with ls command is -l. This will list the files and directories in a long format.
This means it will display the permissions (see chmod), owners, group, size, date and time the file
was last modified, and the filename.
11) mv
mv moves files and directories. It can also be used to rename files or directories.
Syntax: mv [options] source target
If you wanted to rename acetit.txt to acet.txt, you should give the command as:
mv acetit.txt acet.txt
After executing this command, acetit.txt would no longer exist, but a file with name acet.txt would
now exist with the same contents.
12) rm
rm command removes or deletes files from a directory.
Syntax: rm [options] files
In order to remove a file, you must have write permission to the directory where the file is located.
While removing a file which doesn’t have write permission on, a prompt will come up asking you
whether or not you wish to override the write protection.
The -r option is very handy and very dangerous. -r can be used to remove a directory and all its
contents. If you use the -i option, you can possibly catch some disastrous mistakes because it’ll
ask you to confirm whether you really want to remove a file before going ahead and doing it.
13) rmdir
rmdir allows you to remove or delete directories but not their contents. A directory must be empty
in order to remove it using this command.
Syntax: rmdir [options] directories
If you wish to remove a directory and all its contents, you should use rm -r.
Start vi
To use vi on a file, type in vi filename. If the file named filename exists, then the first page
(or screen) of the file will be displayed; if the file does not exist, then an empty file and screen are
created into which you may enter text.
vi filename edit filename starting at line 1
vi -r filename recover filename that was being edited when system crashed
Exit vi
Usually the new or modified file is saved when you leave vi. However, it is also possible
to quit vi without saving the file. The cursor moves to bottom of screen whenever a colon (:) is
typed. This type of command is completed by hitting the <Return> (or <Enter>) key.
:x <Return> quit vi, writing out modified file to file named in original invocation
:wq <Return> quit vi, writing out modified file to file named in original invocation
:q <Return> quit (or exit) vi
:q!<Return> quit vi even though latest changes have not been saved for this vi call
Program: 1
Session – 1
a) Log into the system
b) Use vi editor to create a file called myfile.txt which contains some text.
c) Correct typing errors during creation.
d) Save the file
e) Logout of the system
Solution:
b) Use vi editor to create a file called myfile.txt which contains some text.
vi mytable
Session – 2
Practice the following commands using vi editor with file created in Session – 1
Inserting Text
The following commands allow you to insert and add text. Each of these commands puts
the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the entry of text
Program – 2
Solution:
10
e) Use the sort command to sort the file mytable according to the first field. Call the sorted file
my table ( same name )
The “sort” command sorts information piped into it. There are several options that let you sort
information in a variety of ways. The following list describes the options and their arguments
that may be used to control how sort functions.
1. -o Option: Unix also provides us with special facilities like if you want to write the output
to a new file, output.txt, redirects the output like this or you can also use the built-in sort
option -o, which allows you to specify an output file.
sort inputfile.txt > filename.txt
sort -o filename.txt inputfile.txt
2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag.
the -r flag is an option of the sort command which sorts the input file in reverse order i.e.
descending order by default.
sort -r inputfile.txt
3. -n Option: To sort a file numerically used –n option. -n option is also predefined in Unix as
the above options are. This option is used to sort the file with numeric data present inside.
sort -n filename.txt
4. -nr option: To sort a file with numeric data in reverse order we can use the combination of
11
5. -k Option: Unix provides the feature of sorting a table on the basis of any column number
by using -k option.
sort -k filename.txt
6. -M Option: To sort by month pass the -M option to sort. This will write a sorted list to
standard output ordered by month name.
sort -M filename.txt
g) Use the cut and paste commands to swap fields 2 and 3 of mytable. Call it my table (same
name)
12
Program: 3
A)
a) Login to the system
b) Use the appropriate command to determine your login shell
c) Use the /etc/passwd file to verify the result of step b.
d) Use the who command and redirect the result to a file called myfile1. Use the more command
to see the contents of myfile1.
e) Use the date and who commands in sequence (in one line) such that the output of date will
display on the screen and the output of who will be redirected to a file called myfile2. Use the
more command to check the contents of myfile2.
Solution:
a) Login to the system
b) Use the appropriate command to determine your login shell
echo $SHELL
c) Use the /etc/passwd file to verify the result of step b.
cat /etc/passwd
d) Use the who command and redirect the result to a file called myfile1. Use the more command
to see the contents of myfile1.
who command
The “who” command lets you display the users that are currently logged into your Unix
computer system. It shows the names ofusers that are currently logged in, and may also show
the terminal they're logged in on, and the time they logged in.
who | more
In this example the output of the who command is piped into the more command. This isuseful
when there are a lot of users logged into your computer system, and part of the output of the
who command scrolls off the screen.
who > myfile1 | more
e) Use the date and who commands in sequence (in one line) such that the output of date will
display on the screen and the output of who will be redirected to a file called myfile2. Use the
more command to check the contents of myfile2.
date ; who > myfile2
13
Program: 4
a) Pipe your /etc/passwd file to awk, and print out the home directory of each user.
b) Develop an interactive grep script that asks for a word and a file name and then tells how many
lines contain that word.
c) Repeat
d) Part using awk
Solution:
awk is a programming language that originated at AT&T Bell Laboratories in 1977. Its
name comes from the initials of its designers: Aho, Weinberger, and Kernighan. awk features user-
defined functions, multiple input streams, TCP/IP networking access, and a rich set of regular
expressions. It’s often used to process raw text files, interpreting the data it finds as records and
a) Pipe your /etc/passwd file to awk, and print out the home directory of each user.
cat /etc/passwd | awk ‘ { print $7}’
b) Grep: ---grep is one of many standard UNIX utilities. It searches files for specified words or
patterns. First clear the screen, then type % grep science science.txt
The grep command prints out each line containing the word science.
% grep Science science.txt
The grep command is case sensitive and it distinguishes between Science and science. To ignore
upper/lower case distinctions, use the -i option, i.e. type
% grep -i science science.txt
To search for a phrase or pattern, you must enclose it in single quotes (the apostrophe symbol).
For example to search for spinning top, type
% grep -i ‘spinning top’ science.txt
Some of the other options of grep are:
-v display those lines that do NOT match
-n precede each matching line with the line number
-c print only the total count of matched lines
14
You can use more than one option at a time. For example, the number of lines without the words
science or Science is
% grep -ivc science science.txt
Develop an interactive grep script that asks for a word and a file name and then tells how many
lines contain that word.
echo “Enter a word”
read word
echo “Enter the filename”
read file
nol=grep -c $word $file
echo “ $nol times $word present in the $file”
c) Part using awk
echo “Enter a word”
read word
echo “Enter the filename”
read file
nol=awk ‘/$word/ { print NR }’ Infile
echo “ $nol times $word present in the $file”
15
5. a) Write a shell script that takes a command –line argument and reports on whether it is
directory, a file, or something else
b) Write a shell script that accepts one or more file name as arguments and converts all of them to
uppercase, provided they exist in the current directory.
c) Write a shell script that determines the period for which a specified user is working on the
system.
Solution:
Shell Scripting:
Shell Scripting is an open-source computer program designed to be run by the Unix/Linux
shell. Shell Scripting is a program to write a sequence of commands for the shell to execute. It can
combine lengthy and repetitive sequences of commands into a single and simple script that can be
stored and executed.
Shell:
Shell is a UNIX term for an interface between a user and an Operating System service.
Shell provides users with an interface and accepts commands into the system and executes those
commands which can run automatically and give the program’s output in a shell script.
16
Variable Names
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the
underscore character ( _). A variable is defined as
variable_name = variable_value
Steps to create SHELL Script
1. Create a file using a vi editor and name the script file with extension .sh
2. Start the script with #! /bin/sh (“#!” is an operator called shebang which directs the script
to the interpreter location.)
3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh
Sample Shell script:
#!/bin/sh
echo "Enter your name:"
read name
echo "Hai $name? Welcome to Shell programming"
Command Line arguments
The command-line arguments $1, $2, $3, ...$9 are positional parameters, with $0 pointing
to the actual command, program, shell script, or function and $1, $2, $3, ...$9 as the arguments to
the command.
2 $n These variables correspond to the arguments with which a script was invoked.
Here n is a positive decimal number corresponding to the position of an argument
(the first argument is $1, the second argument is $2, and so on).
4 $* All the arguments are double quoted. If a script receives two arguments, $* is
equivalent to $1 $2.
5 $@ All the arguments are individually double quoted. If a script receives two
arguments, $@ is equivalent to $1 $2.
17
7 $$ The process number of the current shell. For shell scripts, this is the process ID
under which they are executing.
a) Write a shell script that takes a command –line argument and reports on whether it is directory,
a file, or something else
echo "Enter file"
read str
if test -f $str
then echo "File exists and it is an ordinary file"
elif test -d $str
then echo "Directory file"
else
echo "Not exists"
fi
if test -c $str
then echo "Character device files"
fi
b) Write a shell script that accepts one or more file name as arguments and converts all of them to
uppercase, provided they exist in the current directory.
# get filename
echo -n "Enter File Name : "
read fileName
# make sure file exits for reading
if [ ! -f $fileName ]
then
echo "Filename $fileName does not exists"
exit 1
18
fi
# convert uppercase to lowercase using tr command
tr '[A-Z]' '[a-z]' < $fileName
c) Write a shell script that determines the period for which a specified user is working on the
system.
echo “Enter the login of the user”
read name
logindetails=who|grep –w “$name” | grep “tty”
if [ $? –ne 0 ]
then
echo “$name has not logged in yet”
exit
fi
loginhours=echo “$logindetails” | cut –c 26,27
loginminuts=echo “$logindetails” | cut –c 29-30
hoursnow=date | cut –c 12,13
minnow =date | cut –c 15,16
hour=expr $loginhours - $hoursnow
min=expr $loginminuts - $minnow
echo “ $name is working since $hour Hrs - $min Minutes”
19
6. a) Write a shell script that accepts a file name starting and ending line numbers as arguments
and displays all the lines between the given line numbers.
b) Write a shell script that deletes all lines containing a specified word in one or more files supplied
as arguments to it.
Solution:
a) Write a shell script that accepts a file name starting and ending line numbers as arguments and
displays all the lines between the given line numbers.
If [ $# -ne 3 ]
then
echo “Check the arguments once”
lastline=‟wc –l < $1”
if [ $2 –lt $lastline –a $3 -le $lastline ]
then
nline=‟expr $3 -$2 + 1”
echo ““tail +$2 $1 | head -$nline””
else
echo “invalid range specification”
fi
fi
b) Write a shell script that deletes all lines containing a specified word in one or more files supplied
as arguments to it.
if [ $# -lt 1]
then
echo “ Chech the arguments once”
exit
fi
echo “Enter a word”
read word
20
for file in $*
do
grep –iv “$word” $file | tee 1> /dev/null
done
echo “ lines containing given word are deleted”
21
7. a) Write a shell script that computes the gross salary of an employee according to the following
rules:
i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
The basic salary is entered interactively through the key board.
b) Write a shell script that accepts two integers as its arguments and computers the value of first
number raised to the power of the second number.
Solution:
i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic
echo enter basic salary
read sal
a=0.1
da=0.9
echo $a
echo "HRA is"
hra=echo 0.1 \* $sal|bc
echo da is
da=echo 0.9\*$sal|bc`
gsal= “expr $hra + $da + $sal”
echo $gsal
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
echo “Enter Basic pay: ”
read sal
a=500
da=0.98
echo $a
echo "HRA is: "
hra=echo 500 \+ $sal|bc
echo “DA is: ”
22
da=echo 0.98\*$sal|bc`
gsal= “expr $hra + $da + $sal”
echo $gsal
b) Write a shell script that accepts two integers as its arguments and computers the value of first
number raised to the power of the second number.
If [ $# -ne 2 ]
then
echo “Check the number of arguments”
count=1
result=1
if [ $2 –ge 0 ]
then
while [ $count –le $2 ]
do
result=`expr $result \* $1`
count=`expr $count + 1`
done
fi
fi
23
8. a)Write an interactive file-handling shell program. Let it offer the user the choice of copying,
removing, renaming, or linking files. Once the user has made a choice, have the program ask the
user for the necessary information, such as the file name, new name and so on.
b) Write shell script that takes a login name as command – line argument and reports when that
person logs in
c) Write a shell script which receives two file names as arguments. It should check whether the
two file contents are same or not. If they are same then second file should be deleted.
Solution:
a)Write an interactive file-handling shell program. Let it offer the user the choice of copying,
removing, renaming, or linking files. Once the user has made a choice, have the program ask the
user for the necessary information, such as the file name, new name and so on.
while true
do
echo "*******MENU*********"
echo "
1. List of files.
2. Copying files.
3. Removing files.
4. Renaming files.
5. Linking files.
press [CTRL+C] TO EXIT"
echo "Enter your choice: "
read ch
case "$ch" in
1) echo "The list of file names."
ls -l || echo "These are file";;
2) echo "Enter the old filename: "
read ofile
echo "Enter the new file name: "
read nfile
cp $ofile $nfile && echo "Copied successfully." || echo "Copied is not possible." ;;
24
b) Write shell script that takes a login name as command – line argument and reports when that
person logs in
if [ $# -lt 1 ]
then
echo improper usage
echo correct usage is: $0 username
exit
fi
logname=$1
while true
25
do
who|grep "$logname">/dev/null
if [ $? = 0 ]
then
echo $logname has logged in
echo "$logname">>sh01log.txt
date >>sh01log.txt
echo "Hi" > mesg.txt
echo "$logname" >> mesg.txt
echo "Have a Good Day" >> mesg.txt
mail "$logname" < mesg.txt
exit
else
sleep 60 fi done
c) Write a shell script which receives two file names as arguments. It should check whether the
two file contents are same or not. If they are same then second file should be deleted.
echo “enter first file name”
read file1
echo “ enter second file name”
read file2
cmp file1 file2 > file3
if [ -z $file1 ] rm file2
fi
echo “duplicate file deleted successfully”
26
9. a) Write a shell script that displays a list of all the files in the current directory to which the user
has read, write and execute permissions.
b) Develop an interactive script that ask for a word and a file name and then tells how many times
that word occurred in the file.
c) Write a shell script to perform the following string operations:
i) To extract a sub-string from a given string.
ii) To find the length of a given string.
Solution:
a) Write a shell script that displays a list of all the files in the current directory to which the user
has read, write and execute permissions.
echo "List of files which have Read, Write and Execute permissions. "
for file in *
do
if [ -f $file ]
then
if [ -r $file -a -w $file -a -x $file ]
then
ls -l $file
fi
fi
done
b) Develop an interactive script that ask for a word and a file name and then tells how many times
that word occurred in the file.
echo " Enter the word to be searched: "
read word
echo "Enter the source filename: "
read flname
echo "The no. of times the word ['$word'] occurred in the file: "
grep -o $word $flname|wc -l
echo "The line number that contains ['$word'] is: "
grep -c $word $flname
27
28
10. Write a C program that takes one or more file or directory names as command line input and
reports the following information on the file:
i) File type ii)Number of links iii)Read, write and execute permissions
iv) Time of last access
(Note: Use stat/fstat system calls)
Solution:
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fp;
struct stat buf;
fp=open("foss10.txt",O_RDONLY|O_CREAT,600);
if(fp!=-1)
{
if(fstat(fp,&buf)==0)
{
printf("File mode is: %u",buf.st_mode);
printf("\nFile size is: %d bytes",buf.st_size);
printf("\nFile inode is: %d",buf.st_ino);
printf("\nNo. of links: %d",buf.st_nlink);
printf("\nLast modified time is: %u",buf.st_ctime);
printf("\nFile Permissions\n");
printf("File Permissions: \t");
printf((S_ISDIR(buf.st_mode)) ? "d" : "-");
printf((buf.st_mode & S_IRUSR) ? "r" : "-");
printf((buf.st_mode & S_IWUSR) ? "w" : "-");
printf((buf.st_mode & S_IXUSR) ? "x" : "-");
29
}
else
printf("Error in fstat() System call");
}
else
printf("Error in open() System call");
}
30
b) cp command
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
void main()
{
int fp1,fp2;
31
char buf[600];
fp1=open("E:\\foss11.txt",O_RDWR);
fp2=open("E:\\ test.txt",O_RDWR);
read(fp1,buf,sizeof(buf));
write(fp2,buf,sizeof(buf));
close(fp1);
close(fp2);
}
32
12. Write a C program that simulates ls Command (Use system calls / directory API)
Solution:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>
void main()
{
DIR *dp;
struct dirent *dirp;
dp=opendir(".");
while(dirp=(readdir(dp)!=NULL))
{
if(dirp->d_ino==0)
continue;
else
printf("%s \n",dirp->d_name);
}
}
33
13. Write a shell script to accept the name of the file from standard input and perform the following
tests on it a) File executable b) File readable c) File writable d) Both readable & writable
Solution:
There are three specific permissions on Unix-like (including Linux / Mac OS x) systems
that apply to each user or class:
The read permission (r), which grants the ability to read a file. When set for a directory,
this permission grants the ability to read the names of files in the directory
The write permission (w), which grants the ability to modify a file. When set for a
directory, this permission grants the ability to modify entries in the directory. This includes
creating files, deleting files, and renaming files
The execute permission (x), which grants the ability to execute a file. This permission
must be set for executable binaries in order to allow the operating system to run them.
When set for a directory, this permission grants the ability to traverse its tree in order to
access files or subdirectories, but not see files inside the directory (unless read is set).
1. Open vi editor to enter shell scrip and save as foss13.sh
$ vi foss13.sh
echo "Enter File name : "
read fname
# Find out if file has write permission or not
[ -w $fname ] && WP="Write = Yes" || WP="Write = No"
# Find out if file has excute permission or not
[ -x $fname ] && XP="Execute = Yes" || XP="Execute = No"
# Find out if file has read permission or not
[ -r $fname ] && RP="Read = Yes" || RP="Read = No"
echo "$file Permissions are"
echo "$WP"
echo "$RP"
echo "$XP"
34
14. Write an awk program to print sum, avg of student’s marks list.
Use the awk command
Solution:
Using the studmarks.txt file print out the name of each student and calculate and print the total
marks and percentage that they have.
1. Create a studmarks.txt file
$ vi studemarks.txt
Name S1 S2 S3 S4 S5
Amith 56 65 45 47 62
Rakesh 44 56 57 67 53
Madan 56 57 65 54 55
Paresh 67 56 55 66 70
2. Run the following awk command
$ awk '{sum=0 ; for (i=3 ; i <=NF ; i++) sum += $i ; print $1, sum,
(NF >= 2 ? sum / (NF-2) : 0)}' studmarks.txt
Name 0 0
Amith 275 55
Rakesh 277 55.4
Madan 287 57.4
Paresh 314 62.8
35
15. Write an awk program which will find maximum word and its length in the given input File
Solution:
Procedure:
1. Read file and split the words (via sed)
2. Remove duplicates (via sort | uniq)
3. Prefix each word with it's length (awk)
4. Sort the list by the word length
5. Print the single word with greatest length.
Enter the following command
$ sed 's/ /\n/g' myfile.txt | sort | uniq | awk '{print length, $0}' | sort -nr | head -n 1
36
1. Write a shell script that deletes all lines containing the specified word in one or more files
Supplied as arguments to it.
Solution:
Procedure:
1. Write shell script
2. Create two files with 5 to 6 lines of data as test1.txt and test2.txt
3. Check the no of arguments for shell script
if 0 arguments then print no arguments
else pattern=$1(word will be stored in pattern)
for every filename in given files
Delete the line containing the given word with sed command
sed '/'$pattern'/d' $fname
sed acts as filter if word is a file in any line that will be deleted
‘/’ is used to represent regular expressions
‘/d’ is a delete command in sed
else print file NOT FOUND
Implementation:
1. Create a file with the following shell script and save as foss16.sh
$ vi foss16.sh
#!/bin/bash
if [ $# -lt 2 ]then
echo "Enter at lest two files as input in command line"
else
echo "Enter a word to find: "
read word
for f in $*
do
echo "\n In File $f:\n"
sed /$word/d $f
done
37
fi
2. Create two text files with some text and save as test1.txt and test2.txt
$ cat test1.txt
abc
def
ghi
abc
abc
cccc
$ cat test2.txt
abc
def
ghi
abc
abc
cccc
38
39