OS Lab Manual
OS Lab Manual
PracticalNo:-1
Aim: Execute Unix/Linux Command and Describe the Output.
Theory:
Example:
$cal or
$cal 02 2016
Feb 2016
-a Shows you all files, even files that are hidden. (these files begin with a dot.)
-A List all files including the hidden files. However, does not display the working
directory (.) or the parent directory (..).
-d If an argument is a directory it only lists its name not its contents.
-l Shows you huge amounts of information. (permissions, owners, size and when
lastmodified.)
-p Displays a slash ( / ) in front of all directories.
-r Reverses the order of how the files are displayed.
-R Includes the contents of subdirectories.
Example:
$ ls - l
–rw – r----- 1 student student 23 Jan 16 15:27 file1.txt
Field Explanation:
If first character is – then it is normalfile
If it is d then it isdirectory
Field 1 – File Permissions: Next 9 characters specify the files permission.
Each 3 characters refers to the read, write, execute permissions for user,
group and world In this example, –rw – r ----- indicates read-write permission
for user, read permission for group, and no permission forothers.
Field 2 – Number of links: Second field specifies the number of links for
that file. In this example, 1 indicates only one link to thisfile.
Field 3 – Owner: Third field specifies owner of the file. In this example, this
file is owned by username ‘student’.
Field 4 – Group: Fourth field specifies the group of the file. In this example,
this file belongs to “student” group.
Field 5 – Size: Fifth field specifies the size of file. In this example, ’23′
indicates the file size.
OSV-3141601 .
Field 6 – Last modified date & time: Sixth field specifies the date and time
of the last modification of the file. In this example, ‘Jan 16 15:27′ specifies
the last modification time of thefile.
Field 7 – File or directory name: The last field is the name of the file or
directory. In this example, the file name isfile1.txt
6) exit: It is used to terminate a program, shell or log you out of a network normally.
Syntax: exit
7) echo:
Syntax: echo string
Example:
$ echo “Hi.. Hello UNIX”
Hi.. Hello UNIX
8) who: who command can list the names of users currently logged in, their terminal, the
time they have been logged in, and the name of the host from which they have logged in.
Syntax:who [Options] [file]
Description:
am i Print the username of the invoking user, The 'am' and 'i' must bespace separated
-b Prints time of last system boot.
-d Print deadprocesses.
-H Print column headings above the output.
-l Include idle time as HOURS:MINUTES. An idle time of . indicates activity
within the last minute.
-m Same as who am i.
-q Prints only the usernames and the user count/total number of users loggedin.
Example:
$ who
rks/1 2017-12-20 23:15 (:0.0)
Here first column showsuser name, second shows name of the terminal the user is
working on. Third& fourth column shows date and time of logging, last column
shows machinename.
Example:
$ mkdirtestfolder
The above command will create directory named testfolder under the
currentdirectory. We can also create number of subdirectories with one mkdir
command.
-p Allow users to remove the directory and its parent directories which
becomeempty.
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
Non-printing characters (with the exception of tabs, new-lines and form-feeds)
-v
areprinted visibly.
13) cp:cp command copy files from one location to another. If the destination is an existing
file, then the file is overwritten; if the destination is an existing directory, the file is
copied into the directory (the directory is notoverwritten).
Syntax: cp [options]... source destination
Description:
Here, after cp command contents of both source file and destination files are
same.
It will copy the content of source file to destinationfile.
If the destination file doesn’t exist, it will becreated.
If it exists then it will be overwritten without anywarning.
If there is only one file to be copied then destination can be the ordinary file or
the directoryfile.
Example:
$ cp test1 test2
The above cp command copies the content of test1.txt to test2.txt.
Example:
$ rm test.txt
Remove the file test.txt. If the file is write-protected, you will be prompted to
confirm that you really want to deleteit.
$ rm *
Remove all files in the working directory. If it is write-protected, you will be
prompted before rm removesit.
$ rm -f test.txt
Remove the file test.txt. You will not be prompted, even if the file is write-
protected; if rm can delete the file, itwill.
$ rm -f *
Remove all files in the working directory. rm will not prompt you for any reason
before deletingthem.
$ rm -i *
Attempt to remove every file in the working directory, but prompt before each file
to confirm.
16) grep:It selects and prints the lines from a file which matches a given string or pattern.
Syntax:grep [Options] pattern [file]
Description:
This command searches the specified input fully for a match with the supplied pattern
and displaysit.
While forming the patterns to be searched we can use shell match characters, or
regular expressions.
Let us begin with the simplest example of usage ofgrep.
-i Ignore casedistinctions
OSV-3141601 .
Example:
$ grep "Error" sample.txt
Thissearchesforthestring"Error"inthesampleandprintsallthelinesthathave the
word"Error".
$ grep "string" file1 file2
Searching for a string in multiplefiles.
$ grep -i "Unix" test.txt
The -i option enables to search for a string case insensitively in the give file. It
matches the words like "UNIX", "Unix","unix".
$ grep -w "world" test.txt
By default, grep matches the given string/pattern even if it found as a substring in
a file. The -w option to grep makes it match only the wholewords.
$ grep -c "sting" test.txt
We can find the number of lines that matches the givenstring/pattern
$ grep -l "string" *
We can just display the files that contain the givenstring/pattern.
$ grep -n "string" file.txt
We can make the grep command to display the position of the line which contains
the matched string in a file using the –n option
Command Exercise:
1. Perform following commands in UNIX/LINUX.
(1) ps (2) ls (3) unam (4) head (5) tail (6) tty
(7) cal (8) diff (9) cut (10) pwd (11) who (12) paste
(13) find (14) kill (15) date (16) history (17) cmp (18) wc
(19) touch (20) cat (21) cp (22) mv (23) mkdir (24) cd
(25) rmdir (26) rm* (27) set (28) chmod (29) ln (30) man
Practical No:-2
Theory:
There are many ways to edit files in UNIX. Editing files using the screen-oriented text
editor vi is one of the best ways. This editor enables you to edit lines in context with other
lines in the file.
vi is generally considered the de facto standard in UNIX editors because −
It's usually available on all the flavors of UNIX system.
Its implementations are very similar across the board.
It requires very few resources.
It is more user-friendly than other editors such as the edor the ex.
You can use the vi editor to edit an existing file or to create a new file from scratch. You can
also use this editor to just read a text file.
Starting the vi Editor:
The following table lists out the basic commands to use the vi editor –
Following is an example to create a new file simple if it already does not exist in the current
working directory –
$visimple
“simple” [NewFile]
You will notice a tilde (~) on each line following the cursor. A tilde represents an unused
line. If a line does not begin with a tilde and appears to be blank, there is a space, tab,
newline, or some other non-viewable character present.
You now have one open file to start working on. Before proceeding further, let us understand
a few important concepts.
Operation Modes:
While working with the vi editor, we usually come across the following two modes −
Command mode − This mode enables you to perform administrative tasks such as
saving the files, executing the commands, moving the cursor, cutting (yanking) and
pasting the lines or words, as well as finding and replacing. In this mode, whatever
you type is interpreted as a command.
Insert mode − This mode enables you to insert text into the file. Everything that's
typed in this mode is interpreted as input and placed in the file.
vi always starts in the command mode. To enter text, you must be in the insert mode for
which simply type i. To come out of the insert mode, press the Esc key, which will take you
back to the command mode.
Hint − If you are not sure which mode you are in, press the Esc key twice; this will take you
to the command mode. You open a file using the vi editor. Start by typing some characters
and then come to the command mode to understand the difference.
Getting Out of vi:
The command to quit out of vi is:q. Once in the command mode, type colon, and 'q',
followed by return. If your file has been modified in any way, the editor will warn you of
this, and not let you quit. To ignore this message, the command to quit out of vi without
saving is :q!. This lets you exit vi without saving any of the changes.
The command to save the contents of the editor is :w. You can combine the above command
with the quit command, or use :wq and return.
The easiest way to save your changes and exit vi is with the ZZ command. When you are in
the command mode, type ZZ. The ZZ command works the same way as the :wq command.
If you want to specify/state any particular name for the file, you can do so by specifying it
after the :w. For example, if you wanted to save the file you were working on as another
filename called filename2, you would type :w filename2 and return.
Moving within a File:
To move around within a file without affecting your text, you must be in the command mode
(press Esc twice). The following table lists out a few commands you can use to move around
one character at a time –
Editing Files:
To edit the file, you need to be in the insert mode. There are many ways to enter the insert
mode from the command mode –
Deleting Characters:
Here is a list of important commands, which can be used to delete characters and lines in an
open file –
As mentioned above, most commands in vi can be prefaced by the number of times you want
the action to occur. For example, 2x deletes two characters under the cursor location
and 2dddeletes two lines the cursor is on.
It is recommended that the commands are practiced before we proceed further.
Change Commands:
You also have the capability to change characters, words, or lines in vi without deleting
them. Here are the relevant commands –
Program Exercise:
1. Write a shell script to print “Hello World”.
OSV-3141601 .
Review Questions:
1. What is VI Editor?
2. What is Shell script?
3. Write a Shell script with an example.
Practical No:-3
Theory:
While writing a shell script, there may be a situation when you need to adopt one path out of
the given two paths. So you need to make use of conditional statements that allow your
program to make correct decisions and perform the right actions.
Unix Shell supports conditional statements which are used to perform different actions based
on different conditions. We will now understand two decision-making statements here
The if...else statement
The case...esac statement
Theif...else statements:
If else statements are useful decision-making statements which can be used to select an
option from a given set of options.
Unix Shell supports following forms of if…else statement −
if...fi statement
if...else...fi statement
if...elif...else...fi statement
if...fi statement
The if...fi statement is the fundamental control statement that allows Shell to make
decisions and execute statements conditionally.
Syntax:
if [ expression ]
then
Statement(s) to be executed if expression is true
Fi
The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false then no statement would be
executed. Most of the times, comparison operators are used for making decisions.
It is recommended to be careful with the spaces between braces and expression. No
space produces a syntax error.
If expression is a shell command, then it will be assumed true if it returns 0after
execution. If it is a Boolean expression, then it would be true if it returns true.
Example:
a=10
OSV-3141601 .
b=20
if[ $a == $b ]
then
echo"a is equal to b"
fi
if[ $a != $b ]
then
echo"a is not equal to b"
fi
a is not equal to b
if...else...fi statement
The if...else...fi statement is the next form of control statement that allows Shell to
execute statements in a controlled way and make the right choice.
Syntax:
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
Fi
The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false, then no statement will be
executed.
Example:
The above example can also be written using the if...else statement as follows –
a=10
b=20
if[ $a == $b ]
then
echo"a is equal to b"
else
echo"a is not equal to b"
fi
if...elif...else...fi statement
The if...elif...fi statement is the one level advance form of control statement that allows
Shell to make correct decision out of several conditions.
Syntax:
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
Fi
This code is just a series of if statements, where each if is part of the elseclause of the
previous statement. Here statement(s) are executed based on the true condition, if none
of the condition is true then else block is executed.
Example:
a=10
b=20
if[ $a == $b ]
then
echo"a is equal to b"
elif[ $a -gt $b ]
then
echo"a is greater than b"
elif[ $a -lt $b ]
then
echo"a is less than b"
else
echo"None of the condition met"
fi
a is less than b
OSV-3141601 .
Program Exercise:
1. Write a shell script to generate marksheet of a student. Take 3 subjects, calculate and
display total marks, percentage and Class obtained by the student.
2. Write a shell script to find the largest among the 3 given numbers in UNIX / Linux.
OSV-3141601 .
Review Questions:
1. What is if.. fi statement?
2. What is difference between if...else...fi and if...elif...else...fi statement?
Practical No:-4
Theory:
You can use multiple if...elif statements to perform a multiway branch. However, this is not
always the best solution, especially when all of the branches depend on the value of a single
variable.
Shell supports case...esac statement which handles exactly this situation, and it does so more
efficiently than repeated if...elif statements.
Syntax:
The basic syntax of the case...esac statement is to give an expression to evaluate and to
execute several different statements based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found. If
nothing matches, a default condition will be used.
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
Esac
Here the string word is compared against every pattern until a match is found. The
statement(s) following the matching pattern executes. If no matches are found, the case
statement exits without performing any action.
There is no maximum number of patterns, but the minimum is one.
When statement(s) part executes, the command ;; indicates that the program flow should
jump to the end of the entire case statement. This is similar to break in the C programming
language.
OSV-3141601 .
Example:
FRUIT="kiwi"
case"$FRUIT"in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
Esac
2. Write a menu driven shell script which will print the following menu and execute the
given task.
a) Display calendar of current month
b) Display today’s date and time
c) Display usernames those are currently logged in the system
d) Display your name at given x, y position
e) Display your terminal number
f) Exit
Review Question
1. What is use case statement?
2. Difference between nested if and case statement.
OSV-3141601 .
Practical No:-5
Theory:
A loop is a powerful programming tool that enables you to execute a set of commands
repeatedly. In this chapter, we will examine the following types of loops available to shell
programmers −
The while loop
The for loop
The until loop
The select loop
while command
do
Statement(s) to be executed if command is true
Done
Here the Shell command is evaluated. If the resulting value is true, given statement(s) are
executed. If command is false then no statement will be executed and the program will
jump to the next line after the done statement.
Example:
Here is an example that uses the while loop to display the numbers zero to nine –
a=0
while[ $a -lt10]
do
echo $a
a=`expr $a + 1`
done
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time for loop executes, the value of the variable var is
set to the next word in the list of words, word1 to wordN.
Example:
Here is an example that uses the for loop to span through the given list of numbers –
#!/bin/sh
forvarin0123456789
do
echo $var
done
0
1
2
3
4
5
6
7
8
OSV-3141601 .
until command
do
Statement(s) to be executed until command is true
Done
Here the Shell command is evaluated. If the resulting value isfalse, given statement(s) are
executed. If the command is true then no statement will be executed and the program
jumps to the next line after the done statement.
Example:
Here is an example that uses the until loop to display the numbers zero to nine –
a=0
until[! $a -lt10]
do
echo $a
a =`expr $a + 1`
done
0
1
2
3
4
5
6
7
8
9
until command
do
Statement(s) to be executed until command is true
Done
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time the for loop executes, the value of the variable
var is set to the next word in the list of words, word1 to wordN.
For every selection, a set of commands will be executed within the loop. This loop was
introduced in ksh and has been adapted into bash. It is not available in sh.
Example:
Here is an example to let the user select a drink of choice –
The menu presented by the select loop looks like the following –
$./test.sh
1) tea
2) coffee
3) water
4) juice
5) apple
6) all
OSV-3141601 .
7) none
#? juice
Available at home
#? none
$
You can change the prompt displayed by the select loop by altering the variable PS3
as follows –
Nesting Loops:
All the loops support nesting concept which means you can put one loop inside another
similar one or different loops. This nesting can go up to unlimited number of times based
on your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the
programming requirement in a similar way −
Nesting while Loops
It is possible to use a while loop as part of the body of another while loop.
Syntax:
2. Write a shell script which will accept a number b and display first n prime numbers as
output.
3. Writ a shell script which will generate first n Fibonacci numbers like 1,1,2,3,5,13…
OSV-3141601 .
4. Write a shell script which will accept different numbers and find sum of its digit.
5. Write a shell script to check entered number is palindrome or not.
OSV-3141601 .
Review Question:
1. What is use of Loops in shell script?
2. Difference between while and until loops.
3. Difference between while and for loops.
Practical No:-6
Theory:
Command line arguments (also known as positional parameters) are the arguments specified
at the command prompt with a command or script to be executed. The locations at the
command prompt of the arguments as well as the location of the command, or the script
itself, are stored in corresponding variables. These variables are special shell variables.
Below picture will help you understand them.
Variable Description
$0 Represents the command or script.
$1 to $9 Represents arguments 1 through 9.
${10} and so on Represents arguments 10 and further.
$# Represents the total number of arguments.
$* Represents all arguments.
$$ Represents the PID of a running script.
[root@rks ~] # ./calculator.sh 9 4
9 + 4 = 13
9–4=5
9 * 4 = 36
9/4=2
9 ** 4 = 6561
[root@rks ~] #
Exercise:
1. Write a shell script to read n numbers as command arguments as sort them in
descending order.
OSV-3141601 .
Review Question:
1. What is command line argument?
2. Why Command Line arguments required?
Practical No:-7
Theory:
In UNIX, all data are stored in repositories called files. For example, the RESOLVE/C++
programs that you write in this course will be stored as UNIX files. You could also use files to
store any reports that you write or to save the e-mail that you receive.
Like in the "real" world, it is not a good idea to have lots of files "lying around" in a
disorganized manner. UNIX allows you to organize your files into directories. A "directory"
is a location where files are kept in a list. For instance, you could create a directory to store all
your files for the first lab and call it Lab1. You could create another directory called Lab2 to
store your files for the second lab. If you are already familiar with either Apple Macintosh
computers or Windows File Manager, just think of UNIX directories as being the same as
folders.
When you login to a UNIX system, the system puts you in your home directory. Your home
directory is the directory that is assigned to you to store all your files. UNIX has commands
that you can use to create and delete files and directories within your home directory. Unix
also gives you commands to change from your home directory to other directories. The
directory that you're in at any given point of time is called your current working directory.
Different file and directory commands:
1) pwd Command:
pwd– Print Working Directory. pwd command prints the full filename of the current
working directory.
Syntax:
pwd [options]
2) cd Command:
cd – Used to change the directory.
Syntax:
cd [directory | ~ | ./ | ../ | - ]
3) ls Command:
ls – Lists the files and directories under current working directory.
Syntax:
ls [Options]... [FILE]
Options:
-l Lists all the files, directories and their mode, Number of links,
owner of the file, file size, Modified date and time and filename.
-t Lists in order of last modification time.
-a Lists all entries including hidden files.
-d Lists directory files instead of contents.
OSV-3141601 .
4) rm Command:
rm – Used to remove/delete the file from the directory.
Syntax:
rm [options..] [file | directory]
Options:
5) mv Command:
mv – It is used to move/rename file from one directory to another. mv command is
different from cp command as it completely removes the file from the source and
moves to the directory specified, where cp command just copies the content from one
file to another.
Syntax:
mv [-f] [-i] OldFileNameNewFileName
Options:
6) cat Command:
cat – Concatenates files and print it on the standard output.
Syntax:
cat [Options] [FILE]...
Options:
-A Show all.
-b Omits line numbers for blank space in the output.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
7) cmp Command:
cmp – It compares two files and tells you which line numbers aredifferent.
Syntax:
cmp [options..] file1 file2
Options:
8) cp Command:
cp – Copy files from one location to another. If thedestination is an existing file, then the
file is overwritten; if the destination isan existing directory, the file is copied into the
directory (the directory is notoverwritten).
Syntax:
cp [Options]... SourceFileNameDestinationFileName
9) echo Command:
echo – Prints the given input string to standard output.
Syntax:
echo [Options..] [String]
Options:
-p Allow users to remove the directory dir name and its parent directories
which become Empty.
Exercise:
1. Write a shell script to display all executable files, directories and zero sized files from
current directory.
OSV-3141601 .
Practical No:-8
Theory:
This isn't very useful, but witha simple change, we can make this into a typical AWK
program:
Functions in awk:
index(string,search)
length(string)
split(string,array,separator)
substr(string,position)
substr(string,position,max)
tolower(string)
toupper(string)
Exercise:
1. Write an awk program using function, which convert each word in a given text into
capital.
OSV-3141601 .
Practical No:-9
Theory:
Process Creation:
Parent process creates children processes, which, in turn create other processes, forming a tree
of processes. Generally, process identified and managed via a process identifier (pid)
Resource sharing
Parent and children share all resources
Children share subset of parent’s resources
Parent and child share no resources
Execution
Parent and children execute concurrently
Parent waits until children terminate
Address space
Child duplicate of parent
Child has a program loaded into it
UNIX examples
fork system call creates new process
exec system call used after a fork to replace the process’ memory space with a new
program
Process Creation:
The only difference between the parent and process after the call to fork() is the return value
from fork().
Exercise:
1. Write a program for process creation using C.
OSV-3141601 .
Review Question:
1. What are various IDs associated with a process?
2. List the system calls used for process management.