Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views55 pages

OS Lab Manual

The document provides a comprehensive guide on various Unix/Linux commands, including their syntax, descriptions, and examples. Key commands covered include cal, clear, pwd, cd, ls, exit, echo, who, mkdir, rmdir, cat, cp, rm, mv, and grep. Additionally, it includes exercises for practicing commands and introduces the VI editor for creating shell scripts.

Uploaded by

2705varshap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views55 pages

OS Lab Manual

The document provides a comprehensive guide on various Unix/Linux commands, including their syntax, descriptions, and examples. Key commands covered include cal, clear, pwd, cd, ls, exit, echo, who, mkdir, rmdir, cat, cp, rm, mv, and grep. Additionally, it includes exercises for practicing commands and introduces the VI editor for creating shell scripts.

Uploaded by

2705varshap
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

OSV-3141601 .

PracticalNo:-1
Aim: Execute Unix/Linux Command and Describe the Output.

Theory:

1) cal: Displays acalendar


Syntax:cal [Options] [month] [year]
Description:
 cal displays a simple calendar. If arguments are not specified, the current month is
displayed. The switching options are asfollows:

-1 Display single (current) month output. (This is the default.)


-3 Display prev/current/next month output.
-s Display Sunday as the first day of the week. (This is the default.)
-m Display Monday as the first day of the week.
-j Display Julian dates (days one-based, numbered from January 1)
-y Display a calendar for the current year.

Example:
$cal or
$cal 02 2016
Feb 2016

Sun Mon Tue Wed Thu Fri Sat


1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29

2) clear: It clears the terminal screen.


Syntax: clear
Description:
 Clear clears your screen if this is possible, including its scroll back buffer.
 Clear ignores any command-line parameters that may be present.

3) pwd:Displays path from root to currentdirectory


Syntax:pwd [options]
Example:
$ pwd
/home/kumar/progs

4) cd: It is used to change the directory.


Syntax: cd [directory]
Description:
 Used to go back one directory on the majority of all UNIX shells. It is important that
the space be between the cd and directory name
Example:
$ pwd
/home/kumar
$ cdprogs
$ pwd
/home/kumar/progs
$ cd ..
/home/kumar

5) ls: Lists the contents of adirectory


Syntax:ls [Options]
Description:

-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.

9) who am i: Print effective user id


Syntax: who am i
Description: Print the user name associated with the current effective user id.
Example:
$ who am i
rks/1 2017-12-20 23:24 (:0.0)
 Here first column showsusername, second shows name of the terminal the user is
working on. Third& fourth column shows date and time of logging, last column
shows machinename.

10) mkdir:This command is used to create a new directory.


Syntax: mkdir [Options] directory
Description:

-m Set permission mode (as in chmod)


-p No error if existing, make parent directories asneeded.
-v Print a message for each created directory.
directory The name of the directory that you wish to create

Example:
$ mkdirtestfolder
 The above command will create directory named testfolder under the
currentdirectory. We can also create number of subdirectories with one mkdir
command.

11) rmdir:It is used to delete/remove a directory and itssubdirectories.


Syntax: rmdir [Options] directory
Description:
 It removes only empty directory.

-p Allow users to remove the directory and its parent directories which
becomeempty.

12) cat:It is used to create, display and concatenate filecontents.


Syntax: cat [Options] [FILE]…
Description:

-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.

 Three uses of the catcommand.


(a) Create newfiles.
(b) Display the contents of an existingfile.
(c) Concatenate the content of multiple files anddisplay.
Example:
$ cat test.txt
OSV-3141601 .

 Above syntax will display the content of test.txt


$ cat> test.txt
 Above syntax creates test.txt and allow us to insert content for thisfile.
 After inserting content you can use ctrl+d to exit thefile.
 If file with same name exist then it will overwrite thatfile.
$cat test.txt
Hi, Welcome to the Lab session of 2140702 OS
$ cat test.txt >> test1.txt
 It can concatenate the contents of two files. For this append output redirection
operator is used.
 The contents of test1.txt will be appended to test.txt

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.

14) rm:It is used to remove/delete the file from the directory.


Syntax: rm [Options..] [file/directory]
Description:
 Files can be deleted with rm. It can delete more than one file with a single
invocation. For deleting a single file we have to use rm command with filename
to bedeleted.
 Deleted file cannot be recovered. rm can’t delete the directories. If we want to
remove all the files from the particular directory we can use the *symbol.

-f Ignore nonexistent files, and never prompt before removing.


-i Prompt before every removal.

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.

15) mv:It is used to move/rename file from one directory to another.


Syntax: mv [Options] OldFileNameNewFileName
Description:
 mv command which is short formove.
 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 toanother.
 mv has two functions: it renames a file and it moves a group of files to a different
directory. mv doesn’t create a copy of the file , it merely renames it. No additional
space is consumed on disk during renaming. For example if we rename a file test1
to test2 and then if we try to read file test1 we will get error message as it is
renamed to test2 there is no existence of file named test1.
Example:
$ cat test1
Hi, Welcome to the Lab session of 2140702 OS
$ mv test1 test2
 rename test1 to test2
 If the destination file doesn’t exist, it will be created. mv can also be used to
rename a directory. A group of files can also be moved to a directory. mv doesn’t
prompt for overwriting destination file if itexists.

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 .

-f Ignore nonexistent files, and never prompt before removing.


-v Invert the sense of matching, to select non-matchinglines.
-w Select only those lines containing matches that form wholewords.
-x Select only matches that exactly match the wholeline.
-c Print a count of matching lines for each input file.

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

2. Perform following advance commands and filters of Linux/UNIX.


(1) Finger (2) grep (3) egrep (4) fgrep
(5) script (6) expr (7) sort (8) more
OSV-3141601 .
Review Questions:
1. Explain different commands in UNIX/Linux.
2. What is shell programming?
OSV-3141601 .

Practical No:-2

Aim: Create shell script using VI Editor.

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 –

Sr. No. Command and Description


1. vi filename – Creates a new file if it already does not exist, otherwise
opens an existing file.
2. vi -R filename – Opens an existing file in the read-only mode.
3. view filename – Opens an existing file in the read-only mode.

Following is an example to create a new file simple if it already does not exist in the current
working directory –

$visimple

The above command will generate the following output –

“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 –

Sr. No. Command and Description


1. K – Moves the cursor up one line
2. J – Moves the cursor down one line
3. H – Moves the cursor to the left one-character position
4. L – Moves the cursor to the right one-character position

The following points need to be considered to move within a file −


 vi is case-sensitive. You need to pay attention to capitalization when using the
commands.
 Most commands in vi can be prefaced by the number of times you want the action to
occur. For example, 2J moves the cursor two lines down the cursor location.
There are many other ways to move within a file in vi. Remember that you must be in the
command mode (press Esc twice). The following table lists out a few commands to move
around the file −
Given below is the list of commands to move around the file.
Control Commands:
The following commands can be used with the Control Key to perform functions as given in
the table below −
OSV-3141601 .

Given below is the list of control commands.

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 –

Sr. No. Command and Description


1. i – Inserts text before the current cursor location
2. I – Inserts text at the beginning of the current line
3. a – Inserts text after the current cursor location
4. A – Inserts text at the end of the current line
5. o – Creates a new line for text entry below the cursor location
6. O – Creates a new line for text entry above the cursor location

Deleting Characters:
Here is a list of important commands, which can be used to delete characters and lines in an
open file –

Sr. No. Command and Description


1. x – Deletes the character under the cursor location
2. X – Deletes the character before the cursor location
3. dw – Deletes from the current cursor location to the next word
4. d^ – Deletes from the current cursor position to the beginning of the
line
5. d$ – Deletes from the current cursor position to the end of the line
6. D – Deletes from the cursor position to the end of the current line
7. dd – Deletes the line the cursor is on

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 –

Sr. No. Command and Description


1. cc – Removes the contents of the line, leaving you in insert mode.
2. cw – Changes the word the cursor is on from the cursor to the
lowercase w end of the word.
3. r – Replaces the character under the cursor. vi returns to the command
mode after the replacement is entered.
4. R - Overwrites multiple characters beginning with the character
currently under the cursor. You must use Esc to stop the overwriting.
5. s – Replaces the current character with the character you type.
Afterward, you are left in the insert mode.
6. S – Deletes the line the cursor is on and replaces it with the new text.
After the new text is entered, vi remains in the insert mode.

Copy and Paste Commands:


You can copy lines or words from one place and then you can paste them at another place
using the following commands –

Sr. No. Command and Description


1. yy – Copies the current line.
2. yw – Copies the current word from the character the lowercase w cursor
is on, until the end of the word.
3. p – Puts the copied text after the cursor.
4. P – Puts the yanked text before the cursor.

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

Aim: Use of conditional statement in UNIX/LINUX.

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

The above script will generate the following result –

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

Upon execution, you will receive the following result –


a is not equal to b

 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

Upon execution, you will receive the following result –

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

Aim: Use of case statement in UNIX/LINUX.

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

Upon execution, you will receive the following result –

New Zealand is famous for kiwi.


Exercise:
1. Write Script, using case statement to perform basic math operation as follows
a) + addition
b) – subtraction
c) x multiplication
d) / division
OSV-3141601 .

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

Aim: Use of loops in UNIX/Linux.

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

 The while loop


The while loop enables you to execute a set of commands repeatedly until some
condition occurs. It is usually used when you need to manipulate the value of a variable
repeatedly.
Syntax:

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

Upon execution, you will receive the following result –


0
1
2
3
4
5
6
7
8
9

 The for loop


The for loop operates on lists of items. It repeats a set of commands for every item in a
list.
Syntax:

forvar in word1 word2 ... wordN


do
Statement(s) to be executed for every word.
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

Upon execution, you will receive the following result –

0
1
2
3
4
5
6
7
8
OSV-3141601 .

 The until loop


The while loop is perfect for a situation where you need to execute a set of commands
while some condition is true. Sometimes you need to execute a set of commands until a
condition is true.
Syntax:

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

Upon execution, you will receive the following result –

0
1
2
3
4
5
6
7
8
9

 The select loop


The select loop provides an easy way to create a numbered menu from which users can
select options. It is useful when you need to ask the user to choose one or more items
from a list of choices.
Syntax:

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 –

select DRINK in tea cofee water juice appe all none


do
case $DRINK in
tea|coffee|water|all)
echo"Go to canteen"
;;
juice|apple)
echo"Available at home"
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done

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 –

$PS3 = "Please make a selection =>" ; export PS3


$./test.sh
1) tea
2) coffee
3) water
4) juice
5) apple
6) all
7) none
Please make a selection => juice
Available at home
Please make a selection => none
$

 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:

while command1 ; # this is loop1, the outer loop


do
Statement(s) to be executed if command1 is true
while command2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if command2 is true
done
Statement(s) to be executed if command1 is true
Done
Exercise:
1. Write a shell script to find factorial of a given number in Unix/Linux.
OSV-3141601 .

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

Aim:To study about command line arguments in shell script.

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.

Why Command Line arguments required?


1. Telling the command/utility which option to use.
2. Informing the utility/command which file or group of files to process (reading/writing of
files).
Example:
In this example, we are going to write a script that expects the user to provide two
numbers.The script then uses the two numbers as operands of the basic mathematical
operations.
OSV-3141601 .

[root@rks ~] # cat –n calculator.sh


1. #!/bin/bash
2. #This script expects two numbers as command-line arguments
3. #and uses them as operands to the basic arithmetic operations.
4. #Author: Prof. Rohit Singh
5. #Date : 21 Dec. 2017
6. A = `expr $1 + $2`
7. S = $( ($1 – $2) )
8. M = $( ($1 * $2) )
9. D = $( ($1 / $2) )
10. let “P = $1 ** $2”
11. echo “$1 + $2 = $A”
12. echo “$1 – $2 = $S”
13. echo “$1 * $2 = $M”
14. echo “$1 / $2 = $D”
15. echo “$1 ** $2 = $P”
[root@rks ~] #

Lets execute it:

[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

Aim: To study about Executable files and directories.

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 .

-p Puts slash at the end of each directories.


-u List in order of last access time.
-i Display inode information.

4) rm Command:
rm – Used to remove/delete the file from the directory.
Syntax:
rm [options..] [file | directory]
Options:

-f Remove all files in a directory without prompting the user.


-i Interactive. With this option, rm prompts for confirmation before
removing any files.

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:

-f This will not prompt before overwriting (equivalent to -- reply=yes).


mv -f will move the file(s) without prompting even if it is writing over
an existing target.
-i Prompts before overwriting another file.

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:

-c Output differing bytes as characters.


-l Print the byte number (decimal) and the differing byte values(octal) for
each difference.
-s Prints nothing for differing files, return exit status only.

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]

10) mkdir Command:


mkdir – It is used to create one or more directories.
Syntax:
mkdir [Options] directories
Options:

-m Set the access mode for the new directories.


-p Create intervening parent directories if they don't exist.
-v Print help message for each directory created.

11) paste Command:


paste – It is used to paste the content from one file to another file. It isalso used to set
column format for each line.
Syntax:
paste [Options]

Options:

-s Paste one file at a time instead of in parallel.


-d Reuse characters from LIST instead of TABs .

12) rmdir Command:


OSV-3141601 .

rmdir– It is used to delete/remove a directory and its subdirectories.


Syntax:
rmdir [Options..] Directory
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 .

2. Write a shell script to check entered string is palindrome or not.


Review Question:
1. What is file?
2. What is directory?
OSV-3141601 .

Practical No:-8

Aim:To study about AWK.

Theory:

The AWK utility is an interpreted programming language typically used as a dataextraction


and reporting tool. It is a standard feature of most Unix-like operatingSystems.
AWK is an excellent tool for building UNIX/Linux shell scripts. AWK is a programming
language that is designed for processing text-based data,either in files or data streams or
using shells pipes. In other words you cancombine awk with shell scripts or directly use at a
shell prompt.
The essential organization of an AWK program follows the form:
pattern{action}
The pattern specifies when the action is performed. Like most UNIX utilities,AWK is line
oriented. That is, the pattern specifies a test that is performed witheach line read as input. If
the condition is true, then the action is taken. The defaultpattern is something that matches
every line. This is the blank or null pattern.
Twoother important patterns are specified by the keywords "BEGIN" and "END." Asyou
might expect, these two words specify actions to be taken before any lines areread, and after
the last line is read.
The AWK program below adds one line before and one line after the input file.

BEGIN { print "START" }


{ print }
END { print "STOP" }

This isn't very useful, but witha simple change, we can make this into a typical AWK
program:

BEGIN { print "File\tOwner"," }


{ print $8, "\t", $3}
END { print " - DONE -" }

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 .

2. Write a shell script to validate the entered date. (dd-mm-yyyy)


Review Question:
1. What is awk?
2. What is validation?
OSV-3141601 .

Practical No:-9

Aim:Write a program for process creation using C. (Use of gcc compiler).

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:

UNIX Process Creation:


 UNIX fork() creates a process
 Creates a new address space
 Copies text, data, & stack into new address space
 Provides child with access to open files

 Unix exec() allows a child to run a new program


 Unix wait() allows a parent to wait for a child to terminate
Note: In Unix, process creation and management uses multiple, fairly simple system calls.
This provides extra flexibility. If needed, the parent process may contain the code for the
child process to run, so that exec() is not always needed. The child may also set up inter-
process communication with the parent, such as with a pipe before running another
program.

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.

You might also like