Operating System Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Laboratory Manual

For

OPERATING SYSTEM
(2140702)

B.E. (COMPUTER)
SEM IV
Operating System LAB Manual

Table of Contents
Sr. Topic Page
No. No.
1. Introduction 1
1.1 What is kernel? 1
1.2 How to use shell? 2
1.3 What is process? 5
1.4 Why process required? 5
1.5 Linux commands related with process 6
1.6 Redirection of Standard output/input or Input – Output 6
redirection
1.7 Pipes 7
1.8 Filter 7

2. Introduction to shell programming 9


2.1 Variables in Linux 9
2.2 How to define User Defined Variables (UDV) 9
2.3 How to write shell script 11
2.4 How to run shell script 11

3. Control Structure and Looping Structure in Shell Script 13


3.1 If-then-fi for decision making is shell script 13
3.2 test command or [ expr ] 14
3.3 if...else...fi 15
3.4 Loops in Shell Scripts 17
3.5 The read Statement 20

4. Practical List (Perform the below given practicals with the 22


help of shell script.)
Operating System LAB Manual

Its environment provided for user interaction. Shell is a command language interpreter that
executes commands read from the standard input device (keyboard) or from a file. Linux may
use one of the following most popular shells.

Any of the above shell reads command from user (via Keyboard or Mouse) and tells Linux
O/s what users want. If we are giving commands from keyboard it is called command line
interface.

To find your shell type following command.

$ echo $SHELL

1.2 How to use Shell

To use shell (You start to use your shell as soon as you log into your system) you have to
simply type commands. Following is the list of common commands.

Linux Common Commands:

For this Purpose Use this Command Syntax Example ( In front of $

Prompt)

To see date Date $ date

To see who is using system. Who $ who

Print working directory Pwd $ pwd

List name of files in ls or dirs. $ ls

current directory

To create text file cat > { file name } $ cat > myfile

NOTE: Press and hold type your text

CTRL key and press D to when done press

~2~
Operating System LAB Manual

stop or to end file ^D

(CTRL+D)

To text see files cat {file name } $ cat myfile

To display file one full more {file name } $ more myfile

screen at a time

To move or rename mv {file1} {file2} $ mv sales sales.99

file/directory

To create multiple file ln {oldfile} {newfile} $ ln Page1 Book1

Copies with various links.

After this both oldfile

newfile refers to same

name

To remove file rm file1 $ rm myfile

Remove all files in given rm -rf {dirname} $ rm -rf oldfiles

Directory/subdirectory.

Use it very carefully.

To change file access chmod {u|g|o|a} {+|-} $ chmod


{r|w|x} {filename}
permissions u+x,g+wx,o+x myscript

u - User who owns the NOTE: This command set

file permission for file called

g - Group file owner 'myscript' as User (Person

o - User classified as who creates that file or

other directory) has execute

a - All other system user permission (u+x) Group of

+ Set permission file owner can write to this

- Remove permission file as well as execute this

~3~
Operating System LAB Manual

file (g+wx) Others can

r - Read permission only execute file but can

w - Write permission not modify it, Since we

x - Execute permission have not given w (write

permission) to them. (o+x).

Read your mail. Mail $ mail

To See more about who am i $ who am i

currently login person

(i..e. yourself)

To login out logout (OR press CTRL+D) $ logout

(Note: It may ask

you password type

your login password,

In some case this

feature is disabled by

System

Administrator)

Send mail to other person mail {user-name} $ mail nisha

To count lines, words and wc {file-name} $wc myfile


characters of given file

To searches file for line grep {word-to-lookup} $ grep fox Myfile


{filename}
that match a pattern.

To sort file in following sort -r -n -nr $sort myfile


{filename}
order

-r Reverse normal order

-n Sort in numeric order

~4~
Operating System LAB Manual

-nr Sort in reverse

numeric order

To print last | first line of tail - | + { linenumber } $tail +5 myfile


{filename}
given file

To Use to compare files pr {file-name} $pr myfile

1.3 What is Process?

Process is any kind of program or task carried out by your PC. For e.g. $ ls -lR, is command
or a request to list files in a directory and all subdirectory in your current directory. It is a
process. A process is program (command given by user) to perform some Job. In Linux when
you start process, it gives a number (called PID or process-id), PID starts from 0 to 65535.

1.4 Why Process required?

Linux is multi-user, multitasking o/s. It means you can run more than two processes
simultaneously if you wish. For e.g., to find how many files do you have on your system you
may give command like

$ ls / -R | wc -l

This command will take lot of time to search all files on your system. So you can run such
command in Background or simultaneously by giving command like

$ ls / -R | wc -l &

The ampersand (&) at the end of command tells shells start command (ls / -R | wc -l) and run
it in background takes next command immediately. An instance of running command is
called process and the number printed by shell is called process-id (PID), this PID can be
used to refer specific running process.

~5~
Operating System LAB Manual

1.5 Linux Command Related with Process

1.6 Redirection of Standard output/input or Input – Output redirection:

Mostly all command gives output on screen or takes input from keyboard, but in Linux it's
possible to send output to file or to read input from file. For e.g. $ ls command gives output to
screen; to send output to file of ls give command, $ ls > filename. It means put output of ls
command to filename. There are three main redirection symbols >, >>, <

(1) > Redirector Symbol

Syntax: Linux-command > filename

To output Linux-commands result to file. Note that if file already exist, it will be overwritten
else new file is created. For e.g. to send output of ls command give

$ ls > myfiles

Now if 'myfiles' file exist in your current directory it will be overwritten without any type of
warning. (What if I want to send output to file, which is already exist and want to keep
information of that file without losing previous information/data? For this, Read next
redirector)

(2) >> Redirector Symbol

Syntax: Linux-command >> filename

To output Linux-commands result to END of file. Note that If file exist , it will be opened
and new information / data will be written to END of file, without losing previous
information/data, And if file is not exist, then new file is created. For example,

To send output of date command to already exist file give

$ date >> myfiles

(3) < Redirector Symbol

~6~
Operating System LAB Manual

Syntax: Linux-command < filename

To take input to Linux-command from file instead of key-board. For e.g. to take input for cat
command give

$ cat < myfiles

1.7 Pipes

A pipe is a way to connect the output of one program to the input of another program without
any temporary file.

A pipe is nothing but a temporary storage place where the output of one commands stored
and then passed as the input for second command. Pipes are used to run more than two
commands (Multiple commands) from same command line.

Syntax: command1 | command2

1.8 Filter

If a Linux command accepts its input from the standard input and produces its output on
standard output is known as a filter. A filter performs some kind of process on the input and
gives output. For e.g.. Suppose we have file called 'hotel.txt' with 100 lines data, And from

~7~
Operating System LAB Manual

'hotel.txt' we would like to print contains from line number 20 to line number 30 and store
this result to file called 'hlist' then give command

$ tail +20 < hotel.txt | head -n30 >hlist

Here head is filter which takes its input from tail command (tail command start selecting
from line number 20 of given file i.e. hotel.txt) and passes this lines to input to head, whose
output is redirected to 'hlist' file.

~8~
Operating System LAB Manual

2. Introduction to Shell Programming

Shell program is series of Linux commands. Shell script is just like batch file is MS-DOS but
have more power than the MS-DOS batch file. Shell script can take input from user, file and
output them on screen. Useful to create our own commands that can save our lots of time and
to automate some task of day today life.

2.1 Variables in Linux

Sometimes to process our data/information, it must be kept in computers RAM memory.


RAM memory is divided into small locations, and each location had unique number called
memory location/address, which is used to hold our data. Programmer can give a unique
name to this memory location/address called memory variable or variable (It’s a named
storage location that may take different values, but only one at a time). In Linux, there are
two types of variable

1) System variables - Created and maintained by Linux itself. This type of variable defined
in capital letters.

2) User defined variables (UDV) - Created and maintained by user. This type of variable
defined in lower letters.

Some System variables:

You can see system variables by giving command like $ set, some of the important System
variables are

2.2 How to define User defined variables (UDV)

To define UDV use following syntax

Syntax: variablename=value

For example,

~9~
Operating System LAB Manual

$ no=10

$ vech=Bus

To print value of a variable write:

$echo $vech

$echo $no

Rules for Naming variable name (Both UDV and System Variable)

(1) Variable name must begin with Alphanumeric character or underscore character (_),
followed by one or more Alphanumeric character. For e.g. Valid shell variable are as follows

HOME

SYSTEM_VERSION

vech

no

(2) Don't put spaces on either side of the equal sign when assigning value to variable. For e.g.
in following variable declaration there will be no error

$ no=10

But here there will be problem for following

$ no =10

$ no= 10

$ no = 10

(3) Variables are case-sensitive, just like filename in Linux. For e.g.

$ no=10

$ No=11

$ NO=20

$ nO=2

Above all are different variable name, so to print value 20 we have to use $ echo $NO and
Not any of the following

$ echo $no # will print 10 but not 20

$ echo $No # will print 11 but not 20

~ 10 ~
Operating System LAB Manual

$ echo $nO # will print 2 but not 20

(4) You can define NULL variable as follows (NULL variable is variable which has no value
at the time of definition) For e.g.

$ vech=

$ vech=""

Try to print it's value $ echo $vech , Here nothing will be shown because variable has no
value i.e. NULL variable.

(5) Do not use ?,* etc, to name your variable names.

2.3 How to write shell script

Now we write our first script that will print "Knowledge is Power" on screen. To write shell
script you can use in of the Linux's text editor such as vi or mcedit or even you can use cat
command. Here we are using cat command you can use any of the above text editor. First
type following cat command and rest of text as its

$ cat > first

# My first shell script

clear

echo "Knowledge is Power"

Press Ctrl + D to save. Now our script is ready. To execute it type command

$ ./first

This will give error since we have not set Execute permission for our script first; to do this
type command

$ chmod +x first

$ ./first

First screen will be clear, then Knowledge is Power is printed on screen. To print message of
variables contains we user echo command, general form of echo command is as follows

echo "Message"

echo "Message variable1, variable2....variableN"

2.4 How to Run Shell Scripts

~ 11 ~
Operating System LAB Manual

Because of security of files, in Linux, the creator of Shell Script does not get execution
permission by default. So if we wish to run shell script we have to do two things as follows

(1) Use chmod command as follows to give execution permission to our script

Syntax: chmod +x shell-script-name

OR Syntax: chmod 777 shell-script-name

(2) Run our script as

Syntax: ./your-shell-program-name

For e.g.

$ ./first

Here '.'(dot) is command, and used in conjunction with shell script. The dot(.) indicates to
current shell that the command following the dot(.) has to be executed in the same shell i.e.
without the loading of another shell in memory. Or you can also try following syntax to run
Shell Script

Syntax: bash &nbsh;&nbsh; your-shell-program-name

OR /bin/sh &nbsh;&nbsh; your-shell-program-name

specify complete path of your script whenever you want to run it from other directories like
giving following command

$ /bin/sh/home/vivek/first

~ 12 ~
Operating System LAB Manual

3. Control Structure and Looping Structure in Shell Script

3.1 If-then-fi for decision making is shell script

Before making any decision in Shell script you must know following things Type bc at $
prompt to start Linux calculator program

$ bc

After this command bc is started and waiting for you commands, i.e. give it some calculation
as follows type 5 + 2 as

5+2

7 is response of bc i.e. addition of 5 + 2 you can even try

5-2

5/2

Now what happened if you type 5 > 2 as follows

5>2

0 (Zero) is response of bc, How? Here it compare 5 with 2 as, Is 5 is greater than 2, (If I ask
same question to you, your answer will be YES) In Linux (bc) gives this 'YES' answer by
showing 0 (Zero) value. It means whenever there is any type of comparison in Linux Shell It
gives only two answers one is YES and NO is other.

Now will see, if condition which is used for decision making in shell script, If given
condition is true then command1 is executed.

Syntax:

if condition

then

command1 if condition is true or if exit status

of condition is 0 (zero)

...

...

fi

~ 13 ~
Operating System LAB Manual

Here condition is nothing but comparison between two values, for compression we can use
test or [expr] statements or even exist status can be also used. An expression is nothing but
combination of values, relational operator (such as >,<, <> etc) and mathematical operators
(such as +, -, / etc ).

3.2 test command or [ expr ]:

test command or [ expr ] is used to see if an expression is true, and if it is true it return
zero(0),otherwise returns nonzero(>0) for false.

Syntax: test expression OR [ expression ]

Now will write script that determine whether given argument number is positive. Write script
as follows

$ cat > ispostive

#!/bin/sh

# Script to see whether argument is positive

if test $1 -gt 0

then

echo "$1 number is positive"

fi

Run it as follows:

$ chmod +x ispostive

$ ispostive 5

Here o/p: number is positive

$ispostive -45

Here o/p : Nothing is printed

$ispostive

Here o/p: ./ispostive: test: -gt: unary operator expected

For Mathematics use following operator in Shell Script

~ 14 ~
Operating System LAB Manual

For string Comparisons use

Shell also test for file and directory types

Logical Operators

Logical operators are used to combine two or more condition at a time

3.3 if...else...fi

If given condition is true then command1 is executed otherwise command2 is executed.

~ 15 ~
Operating System LAB Manual

Syntax:

if condition

then

command1 if condition is true or if exit status

of condition is 0(zero)

...

...

else

command2 if condition is false or if exit status

of condition is >0 (nonzero)

...

...

fi

Multilevel if-then-else

Syntax:

if condition

then

condition is zero (true - 0)

execute all commands up to elif statement

elif condition1

condition1 is zero (true - 0)

execute all commands up to elif statement

elif condition2

condition2 is zero (true - 0)

execute all commands up to elif statement

else

None of the above condtion,condtion1,condtion2 are true (i.e.

~ 16 ~
Operating System LAB Manual

all of the above nonzero or false)

execute all commands up to fi

fi

3.4 Loops in Shell Scripts

Computer can repeat particular instruction again and again, until particular condition
satisfies. A group of instruction that is executed repeatedly is called a loop.

for loop

Syntax:

for { variable name } in { list }

do

execute one for each item in the list until the list is

not finished (And repeat all statement between do and done)

done

Suppose,

$ cat > testfor

for i in 1 2 3 4 5

do

echo "Welcome $i times"

done

Run it as,

$ chmod +x testfor

$ ./testfor

while loop

Syntax:

while [ condition ]

do

command1

~ 17 ~
Operating System LAB Manual

command2

command3

..

....

done

Loop is executed as long as given condition is true. For eg. Above for loop program can be
written using while loop as

$cat > nt1

#!/bin/sh

#Script to test while statement

if [ $# -eq 0 ]

then

echo "Error - Number missing form command line argument"

echo "Syntax : $0 number"

echo " Use to print multiplication table for given number"

exit 1

fi

n=$1

i=1

while [ $i -le 10 ]

do

echo "$n * $i = `expr $i \* $n`"

i=`expr $i + 1`

done

~ 18 ~
Operating System LAB Manual

Save it and try as

$ chmod +x nt1

$./nt1 7

The case Statement

The case statement is good alternative to multilevel if-then-else-fi statement. It enables you to
match several values against one variable. It’s easier to read and write.

Syntax:

case $variable-name in

pattern1) command

...

..

command;;

pattern2) command

...

..

command;;

patternN) command

...

..

command;;

*) command

...

..

command;;

esac

The $variable-name is compared against the patterns until a match is found. The shell then
executes all the statements up to the two semicolons that are next to each other. The default is
*) and its executed if no match is found. For e.g. create script as follows

~ 19 ~
Operating System LAB Manual

$ cat > car

# if no vehicle name is given

# i.e. -z $1 is defined and it is NULL

# if no command line arg

if [ -z $1 ]

then

rental="*** Unknown vehicle ***"

elif [ -n $1 ]

then

# otherwise make first arg as rental

rental=$1

fi

case $rental in

"car") echo "For $rental Rs.20 per k/m";;

"van") echo "For $rental Rs.10 per k/m";;

"jeep") echo "For $rental Rs.5 per k/m";;

"bicycle") echo "For $rental 20 paisa per k/m";;

*) echo "Sorry, I can not gat a $rental for you";;

esac

Save it by pressing CTRL+D

$ chmod +x car

$ car van

$ car car

$ car Maruti-800

3.5 The read Statement

~ 20 ~
Operating System LAB Manual

Use to get input from keyboard and store them to variable.

Linux Shell Script Tutorial

Syntax: read variable1, variable2... variableN

Create script as

$ cat > sayH

#Script to read your name from key-board

echo "Your first name please:"

read fname

echo "Hello $fname, Lets be friend!"

Run it as follows

$ chmod +x sayH

$ ./sayH

This script first ask you your name and then waits to enter name from the user, Then user
enters name from keyboard (After giving name you have to press ENTER key) and this
entered name through keyboard is stored (assigned) to variable fname.

~ 21 ~

You might also like