unix manual

129
1 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING GITAM INSTITUTE OF TECHNOLOGY GITAM UNIVERSITY UNIX LAB MANUAL Prepared by Under the guidance of 1

Upload: vbhargavir

Post on 09-Mar-2015

448 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Unix Manual

UNIX Lab Manual1

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

GITAM INSTITUTE OF TECHNOLOGY

GITAM UNIVERSITY

UNIX LAB MANUAL

Prepared by Under the guidance of

UTTAM MANDE DR G.APPARAOAssistant Professor Head Of The Department

APPARAO GODI Department of CSEAssistant Professor GITAM Institute of Technology

VENKATESWARLU K GITAM UNIVERSITYAssistant Professor

DIVAKAR AAssistant Professor

******************************************************************************************

1

Page 2: Unix Manual

UNIX Lab Manual2

Index

S.No Contents Page No

1 Lab Objective 3

2 Introduction About Lab 4

3 Guidelines to Students 5

4 List of Syllabus Programs 8

5 Week wise exercises 9

6 Frequently used UNIX commands 28

7 Vi Editor 34

8 About shell 40

9 Introduction to shell programming 44

10 Viva Questions and Answers 83

11 References 98

2

Page 3: Unix Manual

UNIX Lab Manual3

LAB OBJECTIVE

Upon successful completion of this Lab the student will be able to:

1.a. Execute common commands. b. Execute Mail communication commands.

2. Use Vi Editor for creating, updating, viewing and saving the file efficiently 3. Creating directories and files efficiently

4. Grant / revoke the permissions for the user, groups, others efficiently

5. Use piping, redirection, TCC, TTY commands .efficiently

6. Search a pattern using Grep.

7. Implement Sed efficiently

8. Write shell scripts

3

Page 4: Unix Manual

UNIX Lab Manual4

INTRODUCTION ABOUT LAB

There are 67 systems (Compaq Presario) installed in this Lab. Their configurations are as follows:

Processor : Intel® Core™2 duo CPU

RAM : 3.21GB

Hard Disk : 240GB

Mouse : Optical Mouse

Network Interface card : Present

Software

All systems are loaded with Windows XP and they contain putty using which they can connect with

Linux 2.6.18-164.el5

Server name: oracle.gitam.edu

Systems are provided for students in the 1:1 ratio.

Systems are assigned numbers and same system is allotted for students when they do the lab.

4

Page 5: Unix Manual

UNIX Lab Manual5

Guidelines to Students

How to login to the system

Connecting with server

The student has to run putty.exe then putty will be opened ,there he has to enter host name or ip address of Server then click on open

Login in as a user

Then a login form will be displayed and student need to enter login id and password

Then a session will be opened with $ prompt where student can work on server

5

Page 6: Unix Manual

UNIX Lab Manual6

How to Run Shell Scripts

There are two ways you can execute your shell scripts. Once you have created a script file:

Method 1Pass the file as an argument to the shell that you want to interpret your script.

Step 1 : create the script using vi, ex or ed

For example, the script file show has the following lines

Echo Here is the date and time Date

Step 2 : To run the script, pass the filename as an argument to the sh (shell )

$ sh showHere is the date and timeSat Jun 03 13:40:15 PST 2006

Method 2 Make your script executable using the chmod command.

When we create a file, by default it is created with read and write permission turned on and execute permission turned off. A file can be made executable using chmod.

Step 1 : create the script using vi, ex or ed

For example, the script file show has the following lines

echo Here is the date and time date

Step 2 : Make the file executable

6

Page 7: Unix Manual

UNIX Lab Manual7

$ chmod u+x script_file$ chmod u+x show

Step 3 : To run the script, just type the filename

$ showHere is the date and timeSat jun 03 13:40:15 PST 2006

How to run C programs

Step 1 : Use an editor, such as vi, ex, or ed to write the program. The name of the file containing the program should end in .c.

For example, the file show.c contains the following lines :

main(){

printf(“ welcome to GNEC “);}

Step 2 : Submit the file to CC ( the C Compiler )

$ cc show.c

If the program is okay, the compiled version is placed in a file called a.out

Step 3 : To run the program, type a.out

$ a.out Welcome to GNEC

7

Page 8: Unix Manual

UNIX Lab Manual8

List of Lab Exercises as per syllabus of ¾ BTech CSE

2. a ) Practicing common commands .

b ) Mail communication commands .

2 . Vi Editor and its text editing’s and saving this file .

3 . Creating directories and files.

4 . To grant / revoke the permissions for the user , groups , others

5 . Piping redirection ,TCC , TTY commands .

6 . Grep extractions .

7 . Sed implementations.

8 . Shell programming

A ) Sample program

B ) Expressions

C ) Decision making

8

Page 9: Unix Manual

UNIX Lab Manual9

Week Wise Exercises

Week1 Practice Session

1.Log in to the system2.Practice the following basic commands

Command description important Name options

date Synopsis: date [-options] [+format]Diplays the time and date

u

cal Synopsis: cal [[month] year]Displays the calendar for a month or a year.

 

who Synopsis: who [options][am i]Displays all users currently logged into the system

H, u

passwd Synopsis: passwd Changes the user password  

man Synopsis :man commandnameDisplay manual of any command name  

tty Synopsis: tty Displays name of a terminal.  script Synopsis: sript [filename]

Records interactive session.a, g

clear Synopsis: clearClears monitor screen.

a,n, r,s,

whoami Synopsis: whoami displays user information

 

bc Synopsis: bc Calculator.  

Week1 exercises:

1. Change the password.2. Load your work into some file.3. Check any leap year’s feb month.4. Check the users who are not working since 5min.5. Check man man and write your observations.6. Print date in the “Tuesday July 06/07/2010” format.7. Display result of 33/5 in floating value.

9

Page 10: Unix Manual

UNIX Lab Manual10

Week2 Practice Session

1. Log in to the system2. Practice the following file/directory handling utilities with options

COMMAND NAME

Synopsis and discription Important option

fileSynopsis: To view the characteristics of a file.

cat Synopsis: cat [options][file-list]Concatenates files.it may also used to display files or create new files.

n,s,t,u,v,e 

touch Synopsis: touch [options][file list]To view file

vi Synopsis: vi[-options][file-name]Used to create a new file or edit an existing file.

 R

cp

 Synopsis : cp[-options] source destinationCopies files or directories from source to the destination.  p,i,r

mv Synopsis: mv[-options] source destinationMoves a files or directory from source to destination  f,i

ls Synopsis: ls[-options][pathname]Lists all the contents of the directory.

l,d,n,r,t,u,c,p.R,1,i

find Synopsis: find pathname criteriaFinds a file or directory based on criteria.

a,n, r,s,

head Synopsis: head[-options][file-list]Displays lines at the beginning of a file (default is 10 lines).

-N 

tail Synopsis :tail[-options][file-list]Displays lines at the end of a file (default is 10 lines).

-N,+N,b,c,l,r

more Synopsis: more[-options][file-list]Displays the contents of a file one screenful at a time

C,d,f,l,r,s,u,w,lines,+nmbr 

rm Synopsis: rm[options]listRemoves ( deletes) files or directories

f,i,r,

mkdir Synopsis: mkdir [-options] directory-listCreates one or more directories

 P,m

rmdir

Synopsis: rmdir directory-listRemoves ( deletes) directories

 Synopsis: cd[directory] a, g

10

Page 11: Unix Manual

UNIX Lab Manual11

cdChanges the current directory defined by the pathname.

pwd Synopsis: pwd displays the absolute pathname of the current (working)directory

 

wc Synopsis: wc[-options][file-list]Displays the number of lines, words,and characters in a file.

 

Week2 exercises:

1. Create two files and concatenate into file using cat.2. Remove directory without deleting files in directory3. Check the group permissions of any file4. Display the characteristics of any file. 5. Display number of characters in any file.6. Display the first 5 lines and last 20 lines in any file.

Week 3 Practice Session

11

Page 12: Unix Manual

UNIX Lab Manual12

1.Login into system.

2.Execute the mail commands with options.

Command Description OptionsTalk Synopsis:talk user-id [terminal]

Used to create a chatting environment between wo users that are logged into the same or a different system.

Write Synopsis:write user-id [terminal]Used to send a meesage to a receiver logged into the same or a different system from the sender.

Mail Synopsis: mail[receiver-list]Used to read or send email.When it is used without argument, it is in the read mode. When an argument is used,it is in the send mode.

mesg Synopsis: mesg y/nAllows and disallows messges coming from other user

wall Synopsis: wall To send a broadcast message to all users

Week3 lab Excercises :

1. Send mail to other user.2. Read the mail you sent to yourself.3. block the messages from others4. reply to the message5. Use talk command to exchange messages.6. Write command to send message to your friend..7. Find the path of your mbox8.broadcast ”hai” to all

Week 4 Practice Session

12

Page 13: Unix Manual

UNIX Lab Manual13

1. Login into the system.2. Execute Grant and Revoke commands for user group and other.

Command Description OptionsChmod Synopsis:chmod[-option]mode list

Sets or changes the permission of a list of files or directories.

R

Chown Synopsis: chown[-option] owner [:group] listChanges the owner (and the group associated to) a list of files or directories.

R

Chgrp Synopsis:chgrp[-option] group listChanges a group associated with a list of files or directories.

R

Umask Synopsis:umask[mask]Displays or sets the default pemission for newly created files or directories.

Groups Synopsis:groups [user-id]Displays the user’s group.

3.Execute Piping commands Use of Redirection mask Input 0 < file 1 Output 1 > Error w 2 > file2 2 > 1 file2 2 >> file |

Tee who|tee whooct2

Week 4 Exercises:

13

Page 14: Unix Manual

UNIX Lab Manual14

1. Change the permission of any file (add execute permission to group)a. Using symbolic formb. Using Octal form

2. change group of any file?3.set the default write,read permissions to all?4. Using piping display the 5th line to 10th line in any file5.check the group id and users logged in6. Using redirection send the output of any command to file and monitor.7. Change the default permissions of files using umask to rw_r_ _r_ _

Week 5 :

1. Login into the system.2. Execute grep commands r.Command Description Optionse grep Synopsis:

egrep[options]’regexpr’.[file-list]Selects lines that match the regular expression.

b, c, l,n,s,v,x,f

fgrep Synopsis:fgrep[-options]’string’[file-list]Selects lines that match the string.

b,c,i,l,n,s,v,x,f

grep Synopsis:grep[-options]’regexpr’[file-list]Selects lines match the regular expression.

b,c,i,l,n,s,v,x,f

Week 5Exercise:

1.Write a grep (or egrep) command that selects the lines from file 1 that have exactly 3 characters.2. Write a grep (or egrep) command that counts the number of blank lines in file1.

3. Write a grep (or egrep) command that selects the lines from file1 that start with the string “UNIX” and end with the string “UNIX”.

4. Write a grep (or egrep) command that selects the lines from file 1 that start with 1 or more blank spaces and end with 1or more blank spaces.

14

Page 15: Unix Manual

UNIX Lab Manual15

5. Write a grep (or egrep) command that selects the lines from file1 that have atleast 2 digits without any characters in between.

6. Write a grep (or egrep) command that selects the lines from file 1 that start with A to E or M to P,inclusive.

7. Write a command that selects the lines that have only one floating point (not an integer) number. The line should not have any other characters.

8. Write a command that selects the lines that have only one octal number(the octal number should start with zero ).The line should not have any other charaters.

9. Write a command that ,using an input file,creates an output file.the output file is a same as the input file,but it contains only the lines that are a five character palindrome.

10. Use grep to simulate each of the following commands(if possible)a.uniq file1 b.wc -lc.tr “ABC” “***” file1d.sort file1

11.Write a grep (or egrep) command that selects a line from file1 whose last non blank character is A.12. Write a grep (or egrep) command that selects a line from file1 that start with one or more blank spaces.

Week 6

15

Page 16: Unix Manual

UNIX Lab Manual16

1. Log in to the system

2. Practice the following sed commands

Category Command DescriptionLine Number

= Writes the line number

Modify IacdD

Inserts TextAppends TextChanges textDeletes the pattern spaceDeletes the first line of pattern space

Substitute s Substitutes a pattern with a replacement string

Transform y Transforms a set of characters to another set

Input/Output nN

pP

l

Reads the next line into the pattern SpaceAppends the next line in the file to the contents of the pattern spaceSends the content of the pattern space to the standard outputSends only the first line of the pattern space to the standard outputList the contents of the pattern space with nonprinting characters represented by their ASCII codes

Files rw

Reads the contents of the file and appends to the pattern spaceWrites the contents pf the pattern space to a file

Branch :bt

Labels a line to be used by branch(b) and test(t) commandsBranches unconditionally to the label.Branches on successful substitution

Hold Space hHgGx

Copies the contents of the pattern space to the hold spaceAppend the contents of the pattern space to the whole spaceCopies the contents of the hold space to the pattern spaceAppends the contents of the hold space to the pattern spaceSwaps the contents of the pattern space with the contents of the hold space

Quit q Stops processing the input file

Week 6 Exercises:

16

Page 17: Unix Manual

UNIX Lab Manual17

1. Show the result of the sed command Sed “s/bc*./z/” On the following file : aaabbbcccddd aaaabcsssss aaaaabc aabbss

2 . Show the result of the sed command

sed “s/:?.?/z/”

On the following file : :a???????? eeeeeefffff?hhhh aaa::?????? :?.\?

3 . Show the result of the sed command sed “s/^\$[0-9][0-9]$/z/” On the following file : $$$$$$$ $10 abc$ $

4 . what is done by the following command ? sed “32,45s/[()]//g” file1

5 . What is done by the following script ?

10h 11,15H 10,15d 20G

6 . Write ‘sed’ command that deletes the character before the last character in each line in a file .

17

Page 18: Unix Manual

UNIX Lab Manual18

7 . Write ‘sed’ command that deletes the second word in each line in a file .

8 . Write a ‘sed’ command that swaps the first and last character in each line in a file .

9 . Write a ‘sed’ command that delets any integer in each line in a file .

10 . Write a ‘sed’ script to move lines 22 to 33 after line 9 .

11 . Write a ‘sed’ command that extracts the year from a date in the form mm/dd/yy .

12 . Write a ‘sed’ command that , using an input file , creates an output file . Each line in the output file is the same as the corresponding line in the input file except that the first and the last words are swapped .

13 . Can we simulate the following command using only a ‘sed’ command tail -40 file1 .

Week 7 Practice session1. Write shell script for reading two values and display them

Sol:

18

Page 19: Unix Manual

UNIX Lab Manual19

echo "enter the values of a and b"read a becho the values are a=$a b=$b

output:[cse3c23@oracle ~]$ sh s.shenter the values of a and b345 789the values are a=345 b=789

2. Write shell script to display number of files/directories in a directory

Sol: echo "enter the directory name"read nls $n |wc -wexit 0

output: [cse3c23@oracle ~]$ sh s1.shenter the directory name/home/cse3c232[cse3c23@oracle ~]$ lss1.sh s.sh

3. Write a shell script to read two numbers?Sol:

echo enter the values of a b and cread a b cecho the value of a=$aecho the value of b=$becho the value of c=$cd=`expr $a + $b + $c`echo the result is d=$d

output:[cse3c23@oracle ~]$ sh add.shenter the values of a b and c23 56 89the value of a=23the value of b=56the value of c=89the result is d=168

week 7 exercises1. Write a shell script to find G.C.D. of two numbers2. Write a shell script to solve the expression (a+b) 2

3. write shell script to display the terminal id of given user

week8 Practice session

ARMSTRONG

19

Page 20: Unix Manual

UNIX Lab Manual20

1.write a shell script to find an Armstrong numberArmstrong Numberecho enter the numberread ntemp=$nsum=0while [ $n - gt 0 ]dor=`expr $n % 10`sum=`expr $sum + \( $r \* $r \* $r \)`n=`expr $n / 10`doneif [ $temp -eq $sum ]thenecho $temp is armstrongelseecho $temp is not armstrongfiexit 0

Output 1:[cse3c23@oracle ~]$ sh a.shenter the number153153 is armstrongTry thisOutput 2: [cse3c23@oracle ~]$ sh -x a.sh---------------------------------------------------------------------------------------------------------------------

FACTORIAL2.write a shell script to find factorial of a number

FACTORIALecho enter a numberread nsum=1while [ $n -gt 1 ]dosum=`expr $sum \* $n`n=`expr $n - 1`doneecho $sumexit 0

Output 1:[cse3c23@oracle ~]$ sh n.shenter a number6720

20

Page 21: Unix Manual

UNIX Lab Manual21

Try this Output 2:[cse3c23@oracle ~]$ sh -x n.sh

---------------------------------------------------------------------------------------------------------------------

LARGEST NO3.write a shell script to find largest number for three numbers passed with command

LARGEST NUMBERif [ $1 -gt $2 && $1 –gt $3 ]thenx=$1elif [ $2 -gt $3 ]thenx=$2elsex=$3fiecho largest number is $xexit 0

Output 1:[cse3c23@oracle ~]$ sh g.sh 12 34 45largest number is 45Output 2: [cse3c23@oracle ~]$ sh -x g.sh 67 23 45+ '[' 67 -gt 23 ']'+ x=67+ echo largest number is 67largest number is 67+ exit 0---------------------------------------------------------------------------------------------------------------------

PERFECT NO4.write a shell script to find a perfect number

PERFECT NUMBERecho enter a numberread noi=1ans=0while [ $i -le `expr $no / 2` ]doif [ `expr $no % $i` -eq 0 ]thenans=`expr $ans + $i`fii=`expr $i + 1`

21

Page 22: Unix Manual

UNIX Lab Manual22

doneif [ $no -eq $ans ]then echo $no is perfectelseecho $no is not perfectfi

Output 1: [cse3c23@oracle ~]$ sh p.shenter a number3434 is not perfect

Try this Output 2: [cse3c23@oracle ~]$ sh -x p.sh

Week8 exercises

1. Write a program to matrix multiplication for N x N matrix.

2. Write a program to sorting of “N” numbers.

3. Write a program to sorting of “N” strings.

4. Write a program to the given element in the list or not

Week 9Practice section

REVERSE1.write a shell script to find reverse of a numberREVERSE

22

Page 23: Unix Manual

UNIX Lab Manual23

echo enter a numread numrev=0while [ $num -gt 0 ]dok=`expr $num \% 10`l=`expr $rev \* 10`rev=`expr $l + $k`num=`expr $num / 10`doneecho reverse number is $revexit 0

Output 1: [cse3c23@oracle ~]$ sh r.shenter a num12345reverse number is 54321Output 2:try this

[cse3c23@oracle ~]$ sh -x r.sh---------------------------------------------------------------------------------------------------------------------

EVEN AND ODD2.write a shell script to even or oddEVEN OR ODDecho enter a numberread ni=1while [ $i -le $n ]doecho enter termread xif [ `expr $x \% 2` -eq 0 ]thenecho $x is evenelseecho $x is oddfii=`expr $i + 1`done

Output 1:[cse3c23@oracle ~]$ sh eo.shenter a number4enter term33 is odd

23

Page 24: Unix Manual

UNIX Lab Manual24

enter term22 is evenenter term77 is oddenter term88 is even

Output 2: try this [cse3c23@oracle ~]$ sh -x eo.sh---------------------------------------------------------------------------------------------------------------------

FIBONACCI3.write a shell script to display Fibonacci seriesFIBONACCIecho enter the number of termsread nf1=0f2=1i=1echo $f1echo $f2while [ $i -le $n ]dof3=`expr $f1 + $f2`f1=$f2f2=$f3i=`expr $i + 1`echo $f3doneexit 0Output 1:[cse3c23@oracle ~]$ sh fb.shenter the number of terms50112358Output 2:try this [cse3c23@oracle ~]$ sh -x fb.sh---------------------------------------------------------------------------------------------------------------------

PALINDROME

24

Page 25: Unix Manual

UNIX Lab Manual25

4.write a shell script to check palindromePALINDROMEecho enter a numread numrev=0temp=$numwhile [ $num -gt 0 ]dok=`expr $num \% 10`l=`expr $rev \* 10`rev=`expr $l + $k`num=`expr $num / 10`doneif [ $rev -eq $temp ]thenecho $temp is a palindromeelseecho $temp is not a palindromefiexit 0Output 1:[cse3c23@oracle ~]$ sh fbb.shenter a num234234 is not a palindromeOutput 2: try this [cse3c23@oracle ~]$ sh fbb.sh

Week 9 exercises1. Write a shell script that computes the gross salary of a employee according

To the following rulesa) if basic salary is < 1500 then HRA=10% of the basic salary and DA=90% of basicb) if basic salary is >=1500 theen HRA=Rs 500 and DA=98% of basicThe basic salary is entered interactively through the keyboard

2. Write an interactive shell program for copying, removing, renaming & linking3. 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 directory4. Verify executable files in your directory

Week 10 exercises 1.Write a script that will:a. Ask the user's full name—first, last, and middle name.b. Greet the user by his or her first name.c. Ask the user's year of birth and calculate his or her age (use e x p r).

25

Page 26: Unix Manual

UNIX Lab Manual26

d. Ask the user's login name and print his or her user ID ( f r o m / e t c / p a s s w d ).e. Tell the user his or her home directory.f. Show the user the processes he or she is running.g. Tell the user the day of the week, and the current time in nonmilitary time. The outputshould resemble:"The day of the week is Tuesday and the current time is 04:07: 38 PM. "

2.Write a shell script that takes a command line argument and reports on whether it is a directory File, or a regular file, or something else.

3.write a shell script to display the ideal users at their ideal time

4.write the shell script to to take the student marks from text data and send marks to respected students throw mail

Frequently used unix commands

UNIX Commands

Command Description Options

26

Page 27: Unix Manual

UNIX Lab Manual27

. (dot) Synopsis:. CommandReads file from the current shell.

: (colon) Synopsis: (null command)Does nothing (a placeholder). The exit status is always true.

Alias Synopsis: alias name definition alias [name=definition] #Korn and Bash alias[name definition] #C shellLists existing aliases or creates new alias for a command.

Awk Synopsis: awk [options] script [file-list]Selects and processes specified lines in the input file.

-F, -f

Basename Synopsis: basename pathname [argument]Extracts base name or extension of a path name.

Bash Synopsis: bashCreates a new bash shell.

Bc Synopsis: bcCalculator.

Bg Synopsis: bg [job_number]Moves a suspended job to the background.break Synopsis: breakForces a loop to terminate.

breaksw Synopsis: breakswTerminates execution of case commands.

cal Synopsis: cal [[month] year]Displays the calendar for a month or a year.

case Synopsis: case string in pat) command (s);; pat) command (s);; ... esac

Creates a multiway selection.

Command Description Options

27

Page 28: Unix Manual

UNIX Lab Manual28

Cat Synopsis: cat [-options] [file_list] Concatenates files.It may also be ised to display files or create new files.

e ,n, s ,t,u,v

Cd Synopsis: cd [directory]Changes the current directory to the directory defined by the pathname.If the pathname is missing,the home directory becomes the working directory.

Chgrp Synopsis: chgrp [-option] group listChanges a group associated with a list of files or directories.

R

Chmod Synopsis: chmod [-option] mode listSets or changes the permission of a list of files or directories

R

Chown Synopsis: chown [-option] owner [:group]listChanges the owner (and the group associated to) a list of files or directories

R

Clear Synopsis: clearClears monitor screen

Cmp Synopsis: cmp [-options] file1 file2Determines if files are identical

l ,s

Comm Synopsis: comm file1 file2Displays common lines in two files

continue Synopsis: continueContinues with the next iteration of the loop

Cp Synopsis: cp [-options] source destination Copies files or directories from source to destination

Csh Synopsis: cshCreates a new C shell

Ctrl+c Terminates (aborts) a foreground job

Ctrl+z Stops-(suspends) a foreground job

Command Description Options

28

Page 29: Unix Manual

UNIX Lab Manual29

Cut Synopsis: cut [-options] [file-list]Splits files into columns

Date Synopsis: date [-options] [+format]Diplays the time and date

Diff Synopsis: diff [-options] file1 file2 diff [-options] file dir diff [-options] dir file2 diff [-options] dir1 dir2Identifies differences between two files

dirname Synopsis: dirname pathnameExtracts the directory name of a pathname

Grep Synopsis: grep [-options] ‘regexpr’ [file-list] Selects lines that makes the regular expression

b ,c, i , l,n,s,v,x,f

Groups Synopsis: groups [user id]Displays the user’s group

Head Synopsis: head [-options] [file-list]Displays lines at the beginning of a file (default is at 10 lines)

-N

History Synopsis: history –n l-rl command_nameDisplays contents of the command history file

If-then- Else

Synopsis: if command Then ......... Else ......... FiCreate a two way selection

jobs Synopsis: jobsDisplays the list of active objects

kill Synopsis: kill [job_number]Kills a job

ksh Synopsis: kshCreates a new Korn shell

Let Synopsis: let variable=mathematical expressionEvaluates a mathematical expression

Ln Synopsis: ln [-options] source linkLinks the source to destination

S,i,f

Lpr Synopsis: lpr [-options] [file-list] p

Command Description Options

29

Page 30: Unix Manual

UNIX Lab Manual30

Ls Synopsis: ls [-options] [pathname]Lists the contents of a directory

l , d , n ,rt ,u , c ,r,l ,i

Mail Synopsis: mail [receiver-list]Used to read or send mail. When it is used withoutArgument ,it is in the read mode. When an argument is used ,it is in the send mode

Man Synopsis: man command-nameDisplays online documentation for the command

Mkdir Synopsis: mkdir [-options] directory-listCreates one or more directories

P,m

More Synopsis: more [- options] [file-list]Displays the content of a file one screenful at a time.

c, d, f, l, r, s,u, w,lines,+nmbr,+/ptrn

Mv Synopsis: mv [-options] source destinationMoves a file or directory from source to destination orRenames a file or directory.

f, i

onintr Synopsis: onintr [label]Runs a command when a signal received.

passwd Synopsis: passwdChanges the user password.

paste Synopsis: paste [-options] [file-list]Combines lines of files into one single line.

d

print Synopsis: print argument listDisplays contents of a variable or a string

ps Synopsis: psDisplays information about the active processes.

pwd Synopsis: pwdDisplays the absolute pathname of the current (work-ing) directory.

r Synopsis: r line [ -line] command_nameReexecutes (redo) specified command in history file .

read Synopsis: read [options] variable-listReads values and stores them in variables.

Command Description Options

readonly Synopsis: readonly variable –list

30

Page 31: Unix Manual

UNIX Lab Manual31

Makes the variables read only.return Synopsis: return [expression]

Returns from function.rm Synopsis: rm [-options] list

Removes (deletes) files or directories.f, i, r

rmdir Synopsis: rmdir directory-listRemoves (deletes) directories.

script Synopsis: script [filename]Records interactive session.

A

sed Synopsis: sed [-options] script [file-list]Edits specified lines in the input files and processes Them.

n, e, f

Select Synopsis: select variable in list do ..... doneCreates a menu environment.

Set Synopsis: set expressionset var=value #C shellset –o option #Korn and Bashset +o option #Korn and BashSets a value for a variable or sets an option.Also unsets an option in the Korn shell when used with plus option.Sets the positional parameters.

Setenv Synopsis: setenv var = value Setenv variable valueDefines an exportable variable. In C shell,sets a value for an environmental variable.

Shift Synopsis: shift expressionShifts the parameters to the left.

Sleep Synopsis: sleep secondsSleeps for a number of seconds

Sort Synopsis: sort [-options] [field-specifiers] [file-list]Sorts or merges files.

b, c, d,f, m, n,r, t, u

Source Synopsis: source commandExecutes command in current shell.

Stop Synopsis: stop [job_number]Stops (suspends) a background job.

31

Page 32: Unix Manual

UNIX Lab Manual32

Sty Synopsis: sttySets or unsets selected terminal input/output options.

a, g

Switch Synopsis: tail user-id [terminal]Used to create a chatting environment between two users that are logged into the same or a different system.

Tall Synopsis: tail [-options] [file]Displays lines at the end of a file(default is 10 lines).

-N, +N,b, c,l, r

Talk Synopsis: talk user-id [terminal]Used to create a chatting environment between two users that are logged into the same or a different system.

Tee Synopsis: tee [-option] file-listCopies standard input to standard output and at the same time copies to one or more files.

a

32

telnet

Synopsis: telnetConnects the user to the remote computer defined by the argument(domain_name).

test

Synopsis: test argumentsEvaluates a relational,logical,or file expression.

tr

Synopsis: tr [-options] [string1] [string2]Translates (replaces) a set of characters (string1) with another set (string2).

c,d,s

trapSynopsis: trap “action” signalsRuns a command when a signal is received.

ttySynopsis: ttyDisplays name of a terminal.

typesetSynopsis: typeset –attribute variable typeset +attribute variableAssociates (-) and unassociates (+) data attributes,such as numeric and justification,to a variable.

umaskSynopsis: umask [mask]Displays or sets the default permission for newly created files or directories.

unaliasSynopsis: unalias alias-listRemoves some or all aliases.

A(korn and bash)

uname

Synopsis: unameDisplays system data.

a,n, r,s,sr

uniqSynopsis: unique [-options] [input_file]Displays the unique lines in a file.

u,c,d

unsetSynopsis: unset variable unset option #Cshell Unsets the value of a variable or unsets an option.

unsetenvSynopsis: unsetenv variableIn C shell,unsets the value of an environmental variable.

untilSynopsis: until command do body done Repeats the body until the command is successful(exit status 0).

vi Synopsis: vi [-options] [file name]Used to create a new file or edit an existing file.

R

Wc Synopsis: wc[options] [file-list] Displays the number of lines,words,and characters in a file

c, l, w

while Synopsis: while(expression) body endRepeats the body while the expression is successful(exit status 0).

who Synopsis: who [options][am i]Displays all users currently logged into the system.

H, u

whoami Synopsis: whoamiDisplays the id of the user.

write Synopsis: write user-id [terminal]Used to send a message to a receiver logged into the same or a different system from the sender.

Page 33: Unix Manual

UNIX Lab Manual33

Vi editorWhat are Different Editors

33

Page 34: Unix Manual

UNIX Lab Manual34

Sometimes called text editor, a program that enables you to create and edit text files. There are many different types of editors, but they all fall into two general categories:

Line editors: A primitive form of editor that requires you to specify a specific line of text before you can make changes to it. Most edits are a line-at-a-time. Typing, editing, and document display do not occur simultaneously.Two common line editors in unix are sed and ex

Screen editors: Also called full-screen editors, these editors enable you to modify any text that appears on the display screen by moving the cursor to the desired location.

Nowadays, the term editor usually refers to source code editors that include many special features for writing and editing source code.

What is vi?

The default editor that comes with the UNIX operating system is called vi (visual editor). [Alternate editors for UNIX environments include pico and emacs, a product of GNU.]

The UNIX vi editor is a full screen editor and has two modes of operation:

Modes of Vi Editor

There are two modes of Vi works

1. Input Mode: In this mode where any key depressed is entered as text.

2. Command Mode: Where keys are used as commands to act on text

In the command mode, every character typed is a command that does something to the text file being edited; a character typed in the command mode may even cause the vi editor to enter the insert mode. In the insert mode, every character typed is added to the text in the file; pressing the <Esc> (Escape) key turns off the Insert mode.

While there are a number of vi commands, just a handful of these is usually sufficient for beginning vi users. To assist such users, this Web page contains a sampling of basic vi commands. The most basic and useful commands are marked with an asterisk (* or star) in the tables below. With practice, these commands should become automatic.

NOTE: Both UNIX and vi are case-sensitive. Be sure not to use a capital letter in place of a lowercase letter; the results will not be what you expect.

To Get Into and Out Of vi

To Start viTo 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.

34

Page 35: Unix Manual

UNIX Lab Manual35

* vi filename edit filename starting at line 1

vi -r filename recover filename that was being edited when system crashed

To Exit viUsually the new or modified file is saved when you leave vi. However, it is also possible to quit vi without saving the file.

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

Moving the Cursor

Unlike many of the PC and MacIntosh editors, the mouse does not move the cursor within the vi editor screen (or window). You must use the the key commands listed below. On some UNIX platforms, the arrow keys may be used as well; however, since vi was designed with the Qwerty keyboard (containing no arrow keys) in mind, the arrow keys sometimes produce strange effects in vi and should be avoided.

If you go back and forth between a PC environment and a UNIX environment, you may find that this dissimilarity in methods for cursor movement is the most frustrating difference between the two.

In the table below, the symbol ^ before a letter means that the <Ctrl> key should be held down while the letter key is pressed.

* j or <Return> [or down-arrow]

move cursor down one line

* k [or up-arrow] move cursor up one line

* h or <Backspace> [or left-arrow]

move cursor left one character

* l or <Space> [or right-arrow]

move cursor right one character

* 0 (zero) move cursor to start of current line (the one with the cursor)

* $ move cursor to end of current line

35

Page 36: Unix Manual

UNIX Lab Manual36

w move cursor to beginning of next word

b move cursor back to beginning of preceding word

:0<Return> or 1G move cursor to first line in file

:n<Return> or nG move cursor to line n

:$<Return> or G move cursor to last line in file

Screen Manipulation

The following commands allow the vi editor screen (or window) to move up or down several lines and to be refreshed.

^f move forward one screen

^b move backward one screen

^d move down (forward) one half screen

^u move up (back) one half screen

^l redraws the screen

^r redraws the screen, removing deleted lines

Adding, Changing, and Deleting Text

Unlike PC editors, you cannot replace or delete text by highlighting it with the mouse. Instead use the commands in the following tables.

Perhaps the most important command is the one that allows you to back up and undo your last action. Unfortunately, this command acts like a toggle, undoing and redoing your most recent action. You cannot go back more than one step.

* u UNDO WHATEVER YOU JUST DID; a simple toggle

The main purpose of an editor is to create, add, or modify text for a file.

Inserting or Adding TextThe 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 and to put the vi editor back into command mode.

* i insert text before cursor, until <Esc> hit

I insert text at beginning of current line, until <Esc> hit

* a append text after cursor, until <Esc> hit

A append text to end of current line, until <Esc> hit

* o open and put text in a new line below current line, until <Esc> hit

36

Page 37: Unix Manual

UNIX Lab Manual37

* O open and put text in a new line above current line, until <Esc> hit

Changing TextThe following commands allow you to modify text.

* r replace single character under cursor (no <Esc> needed)

R replace characters, starting with current cursor position, until <Esc> hit

cw change the current word with new text, starting with the character under cursor, until <Esc> hit

cNw change N words beginning with character under cursor, until <Esc> hit; e.g., c5w changes 5 words

C change (replace) the characters in the current line, until <Esc> hit

cc change (replace) the entire current line, stopping when <Esc> is hit

Ncc or cNc change (replace) the next N lines, starting with the current line,stopping when <Esc> is hit

Deleting TextThe following commands allow you to delete text.

* x delete single character under cursor

Nx delete N characters, starting with character under cursor

dw delete the single word beginning with character under cursor

dNw delete N words beginning with character under cursor; e.g., d5w deletes 5 words

D delete the remainder of the line, starting with current cursor position

* dd delete entire current line

Ndd or dNd delete N lines, beginning with the current line; e.g., 5dd deletes 5 lines

Cutting and Pasting TextThe following commands allow you to copy and paste text.

yy copy (yank, cut) the current line into the buffer

Nyy or yNy copy (yank, cut) the next N lines, including the current line, into the buffer

p put (paste) the line(s) in the buffer into the text after the current line

Other Commands

37

Page 38: Unix Manual

UNIX Lab Manual38

Searching TextA common occurrence in text editing is to replace one word or phase by another. To locate instances of particular sets of characters (or strings), use the following commands.

/string search forward for occurrence of string in text

?string search backward for occurrence of string in text

n move to next occurrence of search string

N move to next occurrence of search string in opposite direction

Determining Line NumbersBeing able to determine the line number of the current line or the total number of lines in the file being edited is sometimes useful.

:.= returns line number of current line at bottom of screen

:= returns the total number of lines at bottom of screen

^g provides the current line number, along with the total number of lines,in the file at the bottom of the screen

Saving and Reading Files

These commands permit you to input and output files other than the named file with which you are currently working.

:r filename<Return> read file named filename and insert after current line (the line with cursor)

:w<Return> write current contents to file named in original vi call

:w newfile<Return> write current contents to a new file named newfile

:12,35w smallfile<Return> write the contents of the lines numbered 12 through 35 to a new file named smallfile

:w! prevfile<Return> write current contents over a pre-existing file named prevfile

Scrolling through a fileThe vi scrolling commands are useful if you just want to read text sequentially. These commands are all control characters. You will not need to hit the return or enter key after typing the command. The notation ctrl-letter means hold down the control key while pressing the letter key.

ctrl-f Scroll forward a page

ctrl-b Scroll back a page

ctrl-d Scroll forward half a page

ctrl-u Scroll back half a page

38

Page 39: Unix Manual

UNIX Lab Manual39

ctrl-e Scroll forward a linectrl-y Scroll back a line

39

Page 40: Unix Manual

UNIX Lab Manual40

The ShellWhenever you login to a Unix system you are placed in a program called the shell. You can see its prompt at the bottom left of your screen. To get your work done, you enter commands at this prompt.

The shell acts as a command interpreter; it takes each command and passes it to the operating system kernel to be acted upon. It then displays the results of this operation on your screen.

1 . Features provided by the shell

The shell provides you with one or more of the following features. You can:

create an environment that meets your needs write shell scripts define command aliases manipulate the command history automatically complete the command line edit the command line

Some shells provide more of these facilites than others.

2 . Description of different types of shell

There are several different shells available for Unix; the most popular are described here.

You can use any one of these shells if they are available on your system. And you can switch between the different shells once you have found out if they are available.

Bourne shell (sh) C shell (csh) TC shell (tcsh) Korn shell (ksh) Bourne Again SHell (bash)

40

Page 41: Unix Manual

UNIX Lab Manual41

> Bourne shell (sh)

This is the original Unix shell written by Steve Bourne of Bell Labs. It is available on all UNIX systems.

This shell does not have the interactive facilities provided by modern shells such as the C shell and Korn shell. You are advised to to use another shell which has these features.

The Bourne shell does provide an easy to use language with which you can write shell scripts

> C shell (csh)

This shell was written at the University of California, Berkeley. It provides a C-like language with which to write shell scripts - hence its name.

> TC shell (tcsh)

This shell is available in the public domain. It provides all the features of the C shell together with emacs style editing of the command line.

> Korn shell (ksh)

This shell was written by David Korn of Bell labs. It is now provided as the standard shell on Unix systems.

It provides all the features of the C and TC shells together with a shell programming language similar to that of the original Bourne shell.

It is the most efficient shell. Consider using this as your standard interactive shell.

41

Page 42: Unix Manual

UNIX Lab Manual42

> BOURNE AGAIN SHELL (bash)

This is a public domain shell written by the Free Software Foundation under their GNU initiative. Ultimately it is intended to be a full implementation of the IEEE Posix Shell and Tools specification. This shell is widely used within the academic commnity.

bash provides all the interactive features of the C shell (csh) and the Korn shell (ksh). Its programming language is compatible with the Bourne shell (sh).

If you use the Bourne shell (sh) for shell programming consider using bash as your complete shell environment.

Summary of shell facilities : Bourne C TC Korn BASH________________________________________________________

command history No Yes Yes Yes Yes

command alias No Yes Yes Yes Yes

shell scripts Yes Yes Yes Yes Yes

filename completion No Yes* Yes Yes* Yes

command line editing No No Yes Yes* Yes

job control No Yes Yes Yes Yes

________________________________________________________

* not the default setting for this shell

42

Page 43: Unix Manual

UNIX Lab Manual43

3 . Changing your shell

First find out which shell you are using from the shells that are available on your system.

Switch to using another shell Changing to another login shell

> Switch to using another shell

You can switch to another shell for the remainder of your login session. To do this enter the shell command name at the system prompt. For example:

ksh $

This switches you from your current shell to the Korn shell.

> Changing to another login shell

To change the shell that you enter whenever you log in to the system use the chsh (change shell) command. Next time you login you will use the new shell.

You must reset any shell and environment variables that you set in your previous shell's startup file

43

Page 44: Unix Manual

UNIX Lab Manual44

Shell Programming

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.

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 (Its 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

44

Page 45: Unix Manual

UNIX Lab Manual45

NOTE that Some of the above settings can be different in your PC. You can print any of the above

variables contain as follows

$ echo $USERNAME

$ echo $HOME

Caution: Do not modify System variable this can some time create problems.

How to define User defined variables (UDV)

To define UDV use following syntax

Syntax: variablename=value

NOTE: Here 'value' is assigned to given 'variablename' and Value must be on right side = sign For

e.g.

$ no=10 # this is ok

$ 10=no # Error, NOT Ok, Value must be on right side of = sign.

To define variable called 'vech' having value Bus

45

Page 46: Unix Manual

UNIX Lab Manual46

$ vech=Bus

To define variable called n having value 10

$ n=10

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

46

Page 47: Unix Manual

UNIX Lab Manual47

$ 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

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

How to print or access value of UDV (User defined variables)

To print or access UDV use following syntax

Syntax: $variablename

For eg. To print contains of variable 'vech'

$ echo $vech

It will print 'Bus' (if previously defined as vech=Bus) ,To print contains of variable 'n' $ echo $n

It will print '10' (if previously defined as n=10)

Caution: Do not try $ echo vech It will print vech instead its value 'Bus' and $ echo n, It will print

47

Page 48: Unix Manual

UNIX Lab Manual48

n instead its value '10', You must use $ followed by variable name.

Q.1.How to Define variable x with value 10 and print it on screen

$ x=10

$ echo $x

Q.2.How to Define variable xn with value Rani and print it on screen

$ xn=Rani

$ echo $xn

Q.3.How to print sum of two numbers, let's say 6 and 3

$ echo 6 + 3

This will print 6 + 3, not the sum 9, To do sum or math operations in shell use expr, syntax is as

follows Syntax: expr op1 operator op2

Where, op1 and op2 are any Integer Number (Number without decimal point) and operator can be

+ Addition

- Subtraction

/ Division

% Modular, to find remainder For e.g. 20 / 3 = 6 , to find remainder 20 % 3 = 2, (Remember its

integer calculation)

\* Multiplication

$ expr 6 + 3

48

Page 49: Unix Manual

UNIX Lab Manual49

Now It will print sum as 9 , But

$ expr 6+3

will not work because space is required between number and operator (See Shell Arithmetic)

Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)

$x=20

$ y=5

$ expr x / y

Q.5.Modify above and store division of x and y to variable called z

$ x=20

$ y=5

$ z=`expr x / y`

$ echo $z

Note : For third statement, read Shell Arithmetic.

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

49

Page 50: Unix Manual

UNIX Lab Manual50

#

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"

50

Page 51: Unix Manual

UNIX Lab Manual51

How to Run Shell Scripts

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

For e.g.

$ bash first

$ /bin/sh first

Note that to run script, you need to have in same directory where you created your script, if you are

in different directory your script will not run (because of path settings), For eg. Your home directory

51

Page 52: Unix Manual

UNIX Lab Manual52

is ( use $ pwd to see current working directory) /home/vivek. Then you created one script called

'first', after creation of this script you moved to some other directory lets say

/home/vivek/Letters/Personal, Now if you try to execute your script it will not run, since script 'first'

is in /home/vivek directory, to Overcome this problem there are two ways First, specify complete

path of your script when ever you want to run it from other directories like giving following

command

$ /bin/sh /home/vivek/first

Now every time you have to give all this detailed as you work in other directory, this take time and

you have to remember complete path. There is another way, if you notice that all of our programs

(in form of executable files) are marked as executable and can be directly executed from prompt

from any directory (To see executables of our normal program give command $ ls -l /bin or ls -l

/usr/bin) by typing command like

$ bc

$ cc myprg.c

$ cal

etc, How this happed? All our executables files are installed in directory called /bin and /bin directory is set in your PATH setting, Now when you type name of any command at $ prompt, what shell do is it first look that command in its internal part (called as internal command, which is part of Shell itself, and always available to execute, since they do not need extra executable file), if found as internal command shell will execute it, If not found It will look for current directory, if found shell will execute command from current directory, if not found, then Shell will Look PATH setting, and try to find our requested commands executable file in all of the directories mentioned in PATH settings, if found it will execute it, otherwise it will give message "bash: xxxx :command not found", Still there is one question remain can I run my shell script same as these executables. Yes you can, for

52

Page 53: Unix Manual

UNIX Lab Manual53

this purpose create bin directory in your home directory and then copy your tested version of shell

script to this bin directory. After this you can run you script as executable file without using $ ./shell

script-name syntax, Following are steps

$ cd

$ mkdir bin

$ cp first ~/bin

$ first

Each of above command Explanation

ach of above command Explanation

$ cd Go to your home directory

Now created bin directory, to install your own shell

$ mkdir bin script, so that script can be run as independent

program or can be accessed from any directory

$ cp first ~/bin copy your script 'first' to your bin directory

$ first Test whether script is running or not (It will run)

In shell script comment is given with # character. This comments are ignored by your shell.

Comments are used to indicate use of script or person who creates/maintained script, or for some

programming explanation etc. Remember always set Execute permission for you script.

Commands Related with Shell Programming

(1)echo [options] [string, variables...]

53

Page 54: Unix Manual

UNIX Lab Manual54

Displays text or variables value on screen.

Options

-n Do not output the trailing new line.

-e Enable interpretation of the following backslash escaped characters in the strings:

\a alert (bell)

\b backspace

\c suppress trailing new line

\n new line

\r carriage return

\t horizontal tab

\\ backslash

For eg. $ echo -e "An apple a day keeps away \a\t\tdoctor\n"

(2)More about Quotes

There are three types of quotes

" i.e. Double Quotes

' i.e. Single quotes

` i.e. Back quote

1."Double Quotes" - Anything enclose in double quotes removed meaning of that characters (except

\ and $).

2. 'Single quotes' - Enclosed in single quotes remains unchanged.

3. `Back quote` - To execute command.

For eg.

$ echo "Today is date"

54

Page 55: Unix Manual

UNIX Lab Manual55

Can't print message with today's date.

$ echo "Today is `date`".

Now it will print today's date as, Today is Tue Jan ....,See the `date` statement uses back quote,

(3) Shell Arithmetic

Use to perform arithmetic operations For e.g.

$ expr 1 + 3

$ expr 2 - 1

$ expr 10 / 2

$ expr 20 % 3 # remainder read as 20 mod 3 and remainder is 2)

$ expr 10 \* 3 # Multiplication use \* not * since its wild card)

$ echo `expr 6 + 3`

For the last statement not the following points

1) First, before expr keyword we used ` (back quote) sign not the (single quote i.e. ') sign. Back

quote is generally found on the key under tilde (~) on PC keyboards OR To the above of TAB key.

2) Second, expr is also end with ` i.e. back quote.

3) Here expr 6 + 3 is evaluated to 9, then echo command prints 9 as sum

4) Here if you use double quote or single quote, it will NOT work, For eg.

$ echo "expr 6 + 3" # It will print expr 6 + 3

55

Page 56: Unix Manual

UNIX Lab Manual56

$ echo 'expr 6 + 3'

Command Line Processing

Now try following command (assumes that the file "grate_stories_of" is not exist on your disk)

$ ls grate_stories_of

It will print message something like -

grate_stories_of: No such file or directory

Well as it turns out ls was the name of an actual command and shell executed this command when

given the command. Now it creates one question What are commands? What happened when you

type $ ls grate_stories_of? The first word on command line, ls, is name of the command to be

executed. Everything else on command line is taken as arguments to this command. For eg.

$ tail +10 myf

Here the name of command is tail, and the arguments are +10 and myf.

Now try to determine command and arguments from following commands:

$ ls foo

$ cp y y.bak

$ mv y.bak y.okay

$ tail -10 myf

$ mail raj

$ sort -r -n myf

$ date

$ clear

command No. of argument to this command Actual Argument

ls 1 foo

56

Page 57: Unix Manual

UNIX Lab Manual57

cp 2 y and y.bak

mv 2 y.bak and y.okay

tail 2 -10 and myf

mail 1 raj

sort 3 -r, -n, and myf

date 0

clear 0

NOTE: $# holds number of arguments specified on command line. and $* or $@ refer to all

arguments in passed to script. Now to obtain total no. of Argument to particular script, your $#

variable.

Why Command Line arguments required

Let's take rm command, which is used to remove file, But which file you want to remove and how

you will you tail this to rm command (Even rm command does not ask you name of file that would

like to remove). So what we do is we write as command as follows

$ rm {file-name}

Here rm is command and file-name is file which you would like to remove. This way you tail to rm

command which file you would like to remove. So we are doing one way communication with our

command by specifying file-name. Also you can pass command line arguments to your script to

make it more users friendly. But how we address or access command line argument in our script.

Lets take ls command

57

Page 58: Unix Manual

UNIX Lab Manual58

$ ls -a /*

This command has 2 command line argument -a and /* is another. For shell script,

$ myshell foo bar

Shell Script name i.e. myshell

First command line argument passed to myshell i.e. foo

Second command line argument passed to myshell i.e. bar

In shell if we wish to refer this command line argument we refer above as follows

myshell it is $0

foo it is $1

bar it is $2

Here $# will be 2 (Since foo and bar only two Arguments), Please note At a time such 9 arguments

can be used from $0..$9, You can also refer all of them by using $* (which expand to

`$0,$1,$2...$9`) Now try to write following for commands, Shell Script Name ($0), No. of

Arguments (i.e. $#), And actual argument (i.e. $1,$2 etc)

$ sum 11 20

$ math 4 - 7

$d

$ bp -5 myf +20

$ ls *

$ cal

$ findBS 4 8 24 BIG

Shell Script Name No. Of Arguments to script Actual Argument ($1,..$9)

$0 $# $0 $1 $2 $3 $4

58

Page 59: Unix Manual

UNIX Lab Manual59

sum 2 11 20

math 3 4 - 7

d 0

bp 3 -5 myf +20

ls 1 *

cal 0

findBS 4 4 8 24 BIG

For e.g. now will write script to print command ling argument and we will see how to access them

$ cat > demo

#!/bin/sh

#

# Script that demos, command line args

#

echo "Total number of command line argument are $#"

echo "$0 is script name"

echo "$1 is first argument"

echo $2 is second argument"

echo "All of them are :- $*"

Save the above script by pressing ctrl+d, now make it executable

$ chmod +x demo

$ ./demo Hello World

59

Page 60: Unix Manual

UNIX Lab Manual60

$ cp demo ~/bin

$ demo

Note: After this, For any script you have to used above command, in sequence, I am not going to

show you all of the above.

(5)Exit Status

By default in Linux if particular command is executed, it return two type of values, (Values are used

to see whether command is successful or not) if return value is zero (0), command is successful, if

return value is nonzero (>0), command is not successful or some sort of error executing

command/shell script. This value is know as Exit Status of that command. To determine this exit

Status we use $? variable of shell. For eg.

$ rm unknow1file

It will show error as follows

rm: cannot remove `unkowm1file': No such file or directory

and after that if you give command $ echo $?

it will print nonzero value(>0) to indicate error. Now give command

$ ls

$ echo $?

It will print 0 to indicate command is successful. Try the following commands and not down there

exit status

$ expr 1 + 3

$ echo $?

$ echo Welcome

$ echo $?

60

Page 61: Unix Manual

UNIX Lab Manual61

$ wildwest canwork?

$ echo $?

$ date

$ echo $?

$ echon $?

$ echo $?

(6)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

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

0 (Zero) is response of bc, How? Here it compare 5 with 2 as, Is 5 is greater then 2, (If I ask same

question to you, your answer will be YES) In Linux (bc) gives this 'YES' answer by showing 0 (Zero)

61

Page 62: Unix Manual

UNIX Lab Manual62

value. It means when ever there is any type of comparison in Linux Shell It gives only two answer

one is YES and NO is other.

Linux Shell

Meaning Example

Value

Zero Value (0) Yes/True 0

-1, 32, 55

NON-ZERO

No/False anything but not

Value (> 0)

zero

Try following in bc to clear your Idea and not down bc's response

5 > 12

5 == 10

5 != 2

5 == 5

12 < 2

BC's Response (i.e. Linux Shell

Expression Meaning to us Your Answer representation in zero & non-zero

value)

5 > 12 Is 5 greater than 12 NO 0

5 == 10 Is 5 is equal to 10 NO 0

5 != 2 Is 5 is NOT equal to 2 YES 1

5 == 5 Is 5 is equal to 5 YES 1

1<2 Is 1 is less than 2 Yes 1

62

Page 63: Unix Manual

UNIX Lab Manual63

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

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

Following are all examples of expression:

5>2

3+6

3 * 65

a<b

c>5

c > 5 + 30 -1

Type following command (assumes you have file called foo)

$ cat foo

63

Page 64: Unix Manual

UNIX Lab Manual64

$ echo $?

The cat command return zero(0) on successful, this can be used in if condition as follows, Write shell

script as

$ cat > showfile

#!/bin/sh

#

#Script to print file

#

if cat $1

then

echo -e "\n\nFile $1, found and successfully echoed"

fi

Now run it.

$ chmod +x showfile

$./showfile foo

Here

$ ./showfile foo

Our shell script name is showfile($0) and foo is argument (which is $1).Now we compare as follows

if cat $1 (i.e. if cat foo)

Now if cat command finds foo file and if its successfully shown on screen, it means our cat command

is successful and its exist status is 0 (indicates success) So our if condition is also true and hence

statement echo -e "\n\nFile $1, found and successfully echoed" is proceed by shell. Now if cat

command is not successful then it returns non-zero value (indicates some sort of failure) and this

statement echo -e "\n\nFile $1, found and successfully echoed" is skipped by our shell.

Now try to write answer for following

64

Page 65: Unix Manual

UNIX Lab Manual65

1) Create following script

cat > trmif

#

# Script to test rm command and exist status

#

if rm $1

then

echo "$1 file deleted"

fi

(Press Ctrl + d to save)

$ chmod +x trmif

Now answer the following

A) There is file called foo, on your disk and you give command, $ ./trmfi foo what will be output.

B) If bar file not present on your disk and you give command, $ ./trmfi bar what will be output.

C) And if you type $ ./trmfi, What will be output.

(7)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

65

Page 66: Unix Manual

UNIX Lab Manual66

#

# 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 : 5 number is positive

$ispostive -45

Here o/p : Nothing is printed

$ispostive

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

The line, if test $1 -gt 0 , test to see if first command line argument($1) is greater than 0. If it is

true(0) then test will return 0 and output will printed as 5 number is positive but for -45 argument

there is no output because our condition is not true(0) (no -45 is not greater than 0) hence echo

statement is skipped. And for last statement we have not supplied any argument hence error

./ispostive: test: -gt: unary operator expected is generated by shell , to avoid such error we can test

whether command line argument is supplied or not. (See command 8 Script example). test or [ expr

] works with

1.Integer ( Number without decimal point)

2.File types

66

Page 67: Unix Manual

UNIX Lab Manual67

3.Character strings

For Mathematics use following operator in Shell Script

Math- ematical

Normal Arithmetical/

Meaning But in Shell

Operator in

Mathematical Statements

Shell Script

for [ expr ]

for test statement

statement with if

with if command

command

-eq is equal to 5 == 6 if test 5 -eq 6 if expr [ 5 -eq 6 ]

-ne is not equal to 5 != 6 if test 5 -ne 6 if expr [ 5 -ne 6 ]

-lt is less than 5<6 if test 5 -lt 6 if expr [ 5 -lt 6 ]

is less than or

-le 5 <= 6 if test 5 -le 6 if expr [ 5 -le 6 ]

equal to

-gt is greater than 5>6 if test 5 -gt 6 if expr [ 5 -gt 6 ]

is greater than or

-ge 5 >= 6 if test 5 -ge 6 if expr [ 5 -ge 6 ]

equal to

67

Page 68: Unix Manual

UNIX Lab Manual68

NOTE: == is equal, != is not equal.

For string Comparisons use

Operator Meaning

string1 = string2 string1 is equal to string2

string1 != string2 string1 is NOT equal to string2

string1 string1 is NOT NULL or not defined

-n string1 string1 is NOT NULL and does exist

-z string1 string1 is NULL and does exist

Shell also test for file and directory types

Test Meaning

-s file Non empty file

-f file Is File exist or normal file and not a directory

-d dir Is Directory exist and not a file

-w file Is writeable file

-r file Is read-only file

-x file Is file is executable

Logical Operators

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

Operator Meaning

! expression Logical NOT

expression1 -a expression2 Logical AND

expression1 -o expression2 Logical OR

(8)if...else...fi

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

68

Page 69: Unix Manual

UNIX Lab Manual69

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

For eg. Write Script as follows

$ cat > isnump_n

#!/bin/sh

#

# Script to see whether argument is positive or negative

#

if [ $# -eq 0 ]

then

echo "$0 : You must give/supply one integers"

exit 1

69

Page 70: Unix Manual

UNIX Lab Manual70

fi

if test $1 -gt 0

then

echo "$1 number is positive"

else

echo "$1 number is negative"

fi

Try it as follows

$ chmod +x isnump_n

$ isnump_n 5

Here o/p : 5 number is positive

$ isnump_n -45

Here o/p : -45 number is negative

$ isnump_n

Here o/p : ./ispos_n : You must give/supply one integers

$ isnump_n 0

Here o/p : 0 number is negative

Here first we see if no command line argument is given then it print error message as "./ispos_n :

You must give/supply one integers". if statement checks whether number of argument ($#) passed

to script is not equal (-eq) to 0, if we passed any argument to script then this if statement is false

and if no command line argument is given then this if statement is true. The echo command i.e.

echo "$0 : You must give/supply one integers"

| |

| |

70

Page 71: Unix Manual

UNIX Lab Manual71

1 2

1 will print Name of script

2 will print this error message

And finally statement exit 1 causes normal program termination with exit status 1 (nonzero means

script is not successfully run), The last sample run $ isnump_n 0 , gives output as "0 number is

negative", because given argument is not > 0, hence condition is false and it's taken as negative

number. To avoid this replace second if statement with if test $1 -ge 0.

(9)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.

all of the above nonzero or false)

execute all commands up to fi

71

Page 72: Unix Manual

UNIX Lab Manual72

fi

For e.g. Write script as $ cat > elf #!/bin/sh # # Script to test if..elif...else # # if [ $1 -gt 0 ]

then echo "$1 is positive" elif [ $1 -lt 0 ] then echo "$1 is negative" elif [ $1 -eq 0 ]

then echo "$1 is zero" else echo "Opps! $1 is not number, give number" fi Try above

script with $ chmod +x elf $ ./elf 1 $ ./elf -2 $ ./elf 0 $ ./elf a Here o/p for last

sample run: ./elf: [: -gt: unary operator expected ./elf: [: -lt: unary operator expected ./elf: [: -eq:

unary operator expected Opps! a is not number, give number Above program gives error for last

run, here integer comparison is expected therefore error like "./elf: [: -gt: unary operator expected"

occurs, but still our program notify this thing to user by providing message "Opps! a is not number,

give number". (10)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.

(a) 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

72

Page 73: Unix Manual

UNIX Lab Manual73

Run it as,

$ chmod +x testfor

$ ./testfor

The for loop first creates i variable and assigned a number to i from the list of number from 1 to 5,

The shell execute echo statement for each assignment of i. (This is usually know as iteration) This

process will continue until all the items in the list were not finished, because of this it will repeat 5

echo statements. for e.g. Now try script as follows

$ cat > mtable

#!/bin/sh

#

#Script to test for loop

#

#

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

for i in 1 2 3 4 5 6 7 8 9 10

do

73

Page 74: Unix Manual

UNIX Lab Manual74

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

done

Save and Run it as

$ chmod +x mtable

$ ./mtable 7

$ ./mtable

For first run, Above program print multiplication table of given number where i = 1,2 ... 10 is

multiply by given n (here command line argument 7) in order to produce multiplication table as

7*1=7

7 * 2 = 14

...

..

7 * 10 = 70 And for Second run, it will print message -

Error - Number missing form command line argument

Syntax : ./mtable number

Use to print multiplication table for given number

This happened because we have not supplied given number for which we want multiplication table,

Hence we are showing Error message, Syntax and usage of our script. This is good idea if our

program takes some argument, let the user know what is use of this script and how to used it. Note

that to terminate our script we used 'exit 1' command which takes 1 as argument (1Indicates error

and therefore script is terminated)

(b)while loop

Syntax:

while [ condition ]

74

Page 75: Unix Manual

UNIX Lab Manual75

do

command1

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 ]

75

Page 76: Unix Manual

UNIX Lab Manual76

do

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

i=`expr $i + 1`

done

Save it and try as

$ chmod +x nt1

$./nt1 7

Above loop can be explained as follows

Set the value of command line argument to

n=$1

variable n. (Here it's set to 7 )

i=1 Set variable i to 1

This is our loop condition, here if value of i is less

while [ $i -le 10 ] than 10 then, shell execute all statements between

do and done

do Start loop

Print multiplication table as

7*1=7

7 * 2 = 14

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

....

7 * 10 = 70, Here each time value of variable n is

76

Page 77: Unix Manual

UNIX Lab Manual77

multiply be i.

Increment i by 1 and store result to i. ( i.e. i=i+1)

Caution: If we ignore (remove) this statement than

our loop become infinite loop because value of

variable i always remain less than 10 and program

i=`expr $i + 1` will only output

7*1=7

...

...

E (infinite times)

Loop stops here if i is not less than 10 i.e.

done condition of loop is not true. Hence

loop is terminated.

From the above discussion not following points about loops

(a) First, the variable used in loop condition must be initialized, Next execution of the loop begins.

(b) A test (condition) is made at the beginning of each iteration.

(c) The body of loop ends with a statement that modifies the value of the test (condition) variable.

(11) The case Statement

The case statement is good alternative to Multilevel if-then-else-fi statement. It enable you to match

several values against one variable. Its easier to read and write.

Syntax:

case $variable-name in

pattern1) command

...

..

77

Page 78: Unix Manual

UNIX Lab Manual78

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 eg. Create script as follows

$ cat > car

#

# if no vehicle name is given

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

#

78

Page 79: Unix Manual

UNIX Lab Manual79

# 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

Here first we will check, that if $1(first command line argument) is not given set value of rental

variable to "*** Unknown vehicle ***",if value given then set it to given value. The $rental is

compared against the patterns until a match is found. Here for first run its match with van and it will

show output For van Rs.10 per k/m. For second run it print, "For car Rs.20 per k/m". And for last

79

Page 80: Unix Manual

UNIX Lab Manual80

run, there is no match for Maruti-800, hence default i.e. *) is executed and it prints, "Sorry, I can

not gat a Maruti-800 for you". Note that esac is always required to indicate end of case statement.

(12)The read Statement

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

Syntax: read varible1, varible2,...varibleN

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.

(13)Filename Shorthand or meta Characters (i.e. wild cards)

* or ? or [...] is one of such shorthand character.

* Matches any string or group of characters.

80

Page 81: Unix Manual

UNIX Lab Manual81

For e.g. $ ls * , will show all files, $ ls a* - will show all files whose first name is starting with letter

'a', $ ls *.c ,will show all files having extension .c $ ls ut*.c, will show all files having extension .c

but first two letters of file name must be 'ut'.

? Matches any single character.

For e.g. $ ls ? , will show one single letter file name, $ ls fo? , will show all files whose names are 3

character long and file name begin with fo

[...] Matches any one of the enclosed characters.

For e.g. $ ls [abc]* - will show all files beginning with letters a,b,c

[..-..] A pair of characters separated by a minus sign denotes a range;

For eg. $ ls /bin/[a-c]* - will show all files name beginning with letter a,b or c like

/bin/arch /bin/awk /bin/bsh /bin/chmod /bin/cp

/bin/ash /bin/basename /bin/cat /bin/chown /bin/cpio

/bin/ash.static /bin/bash /bin/chgrp /bin/consolechars /bin/csh

But

$ ls /bin/[!a-o]

$ ls /bin/[^a-o]

If the first character following the [ is a ! or a ^ then any character not enclosed is matched i.e. do

not show us file name that beginning with a,b,c,e...o, like

/bin/ps /bin/rvi /bin/sleep /bin/touch /bin/view

/bin/pwd /bin/rview /bin/sort /bin/true /bin/wcomp

/bin/red /bin/sayHello /bin/stty /bin/umount /bin/xconf

/bin/remadmin /bin/sed /bin/su /bin/uname /bin/ypdomainname

/bin/rm /bin/setserial /bin/sync /bin/userconf /bin/zcat

/bin/rmdir /bin/sfxload /bin/tar /bin/usleep

/bin/rpm /bin/sh /bin/tcsh /bin/vi

81

Page 82: Unix Manual

UNIX Lab Manual82

(14)command1;command2

To run two command with one command line.For eg. $ date;who ,Will print today's date followed

by users who are currently login. Note that You can't use $ date who for same purpose, you must

put semicolon in between date and who command.

82

Page 83: Unix Manual

UNIX Lab Manual83

Viva Questions & Answers

1. What  is  a  Make  file?

Ans : Make  file  is  a  utility  in  Unix  to  help  compile  large  programs .  It  helps  by  only compiling  the  portion  of  the  program  that  has  been  changed .

2. Could  you  tell  something  about  the  Unix  System  Kernel?

Ans : The  kernel  is  the  heart  of  the  UNIX  operating  system ,  it’s  responsible for controlling  the  computer’s  resources  and  scheduling  user  jobs  so  that each  one  gets  its fair  share  of  resources .3. How  can  you  tell  what  shell you are  running  on  UNIX system with out using SHELL VARIABLE

Ans :You  can  do  the Echo  $RANDOM . It  will  return  a  undefined  variable  if you  are from  the  C-Shell ,  just  a  return  prompt  if  you  are  from  the  Bourne shell , and  a  5  digit random  numbers  if  you  are  from  the  Korn  shell . You could  also  do  a ps -l  and  look  for the  shell  with  […]

4. What  do you  mean  by  u-area  (user area)  or  u-block?

Ans : This  contains  the  private  data  that  is  manipulated  only  by  the Kernel . This  is  local  to  the  Process ,  i.e.  each  process  is  allocated  a  u-area.

5 . What  scheme  does  the  Kernel  in  Unix System V follow  while choosing  a swap  device  among  the  multiple  swap  devices?

Ans : Kernel  follows  Round  Robin  scheme  choosing  a  swap  device among the  multiple  swap  devices  in  Unix System V .

83

Page 84: Unix Manual

UNIX Lab Manual84

6 . List  the  system  calls  used  for  process  management:

Ans :  System calls                   Description                 fork()     To  create  a  new  process              exec()      To  execute  a  new  program  in  a   process

7 . How  do  you  change  File Access  Permissions?

Ans : Every  file  has  following  attributes:               1.  owner’s  user ID  ( 16 bit integer )               2.  owner’s  group  ID  ( 16 bit integer )               3.  File  access  mode  word                           ‘r w x -r w x- r w x’ (user  permission - group  permission) To change  the  access  mode , we  use chmod (filename,mode).

Example:To change  mode  of  myfile  to ‘rw-rw-r–’  (ie. read ,  write  permission  for user  

8 . Explain   the  layered aspect  of  a  UNIX  ystem . What  are the layers? What does it  mean to  say  they  are  layers?

Ans : A  UNIX  system  has  essentially  three  main  layers :                       1 . The  hardware                       2 . The  operating  system  kernel                       3 . The  user - level  programs  The  kernel  hides  the  system’s  hrdware  underneath  an  abstract , high - level programming  interface .  It  is  responsible for implementing  many of the  facilities that  users and  user - level programs  take  for  granted .The  kerne l assembles  all  of  the  following  UNIX  concepts  from lowe r - level  

9 . What  is  the use  of  ‘grep’  command?

84

Page 85: Unix Manual

UNIX Lab Manual85

Ans : ‘grep’  is  a  pattern  search  command . It searches  for  the  pattern , specified  in  the  command  line  with  appropriate  option ,  in  a  file(s).         Syntax : grep  

         Example : grep  99mx  mcafile

10 . What  difference  between  cmp  and  diff  commands?

Ans : cmp  -  Compares  two  files  byte  by  byte  and  displays  the                      first mismatch.        diff   -  tells  the  changes  to  be  made  to  make  the  files

identical

11 . What  is  the  significance  of  the  “tee”  command ?

Ans : It  reads  the  standard  input  and   sends  it  to  the  standard  output while redirecting  a copy  of  what  it  has  read  to  the  file  specified  by  the user.

12 . Is ‘du’ a command? If so, what is its use?

Ans : Yes ,  it  stands for  ‘disk usage’. With  the  help  of  this  command you  can find  the  disk  capacity  and  free space  of  the  disk.

13 . How  to  terminate  a  process  which  is  running  and  the specialty  on command  kill 0?

Ans: With  the  help  of  kill  command  we  can  terminate  the  process .                     Syntax: kill

                     pid  Kill  0 -  kills  all  processes  in  your  system  except the login  shell.

14. Explain  kill()  and  its  possible  return  values.

85

Page 86: Unix Manual

UNIX Lab Manual86

Ans : There  are  four  possible  results  from  this  call :               1 . ‘kill()’ returns  0. This  implies  tha t a  process  exists  with  the given PID , and  the  system  would  allow  you  to  send  signals  to  it . It  is system - dependent  whether  the  process could  be  a  zombie.             2 .  ‘kill()’  returns  -1 , ‘errno == ESRCH’   either  no  process exists  with the  given  PID , or […]

15 . What  does  the  command  “ $who | sort –logfile > newfile”  do?

Ans : The  input  from  a  pipe  can  be  combined  with  the  input  from  a file . The  trick  is  to  use  the  special  symbol  “-“  (a hyphen)  for  those commands that  recognize  the  hyphen  as  std  input .                   In  the  above  command  the  output  from  who  becomes  the std input  to  sort ,  meanwhile  sort  opens  the  file

16 . What  are  shell  variables ?

Ans  : Shell  variables  are  special  variables ,  a  name-value  pair  created  and maintained  by  the  shell .                  Example :  PATH , HOME , MAIL  and  TERM

17 . How  many  prompts  are  available  in  a  UNIX  system?

Ans : Two  prompts :                          PS1 (Primary Prompt) ,  PS2 (Secondary Prompt).

18 . Is  it  possible  to  create  new  a  file  system  in  UNIX ?

Ans : Use  ‘su’  command .  The  system  asks  for  password  and  when valid entry  is  made  the  user  gains  super  user (admin)  privileges.

19 . How the  Kernel  handles  the  copy  on  write  bit  of  a  page , when  the  bit i s  set?

86

Page 87: Unix Manual

UNIX Lab Manual87

Ans :In  situations  like ,  where  the  copy  on  write  bit  of  a  page  is  set and that  page  is  shared  by  more  than  one  process ,  the  Kernel  allocates  new page  and  copies  the  content  to  the  new  page  and  the other  processes retain  their  references  to  the  old  page .  After  copying the  Kernel  updates the  page […]

20 . Difference  between   the  fork()  and  vfork()  system  call?

Ans : During  the  fork()  system  call  the  Kernel  makes  a  copy  of  the  parent process’s address  space  and  attaches  it  to  the  child  process . But  the  vfork()  system  call  do  not makes  any  copy  of  the  parent’s  address  space, so  it  is  faster  than  the  fork()  system call . The  child  process  as  a  result  of the  vfork() […]

21 . How  the  Kernel  handles  the  fork()  system  call  in  traditional Unix  and in  the  System V  Unix,  while  swapping?

Ans : Kernel  in  traditional  Unix ,  makes  the  duplicate  copy  of  the parent’s address  space  and  attaches  it  to  the  child’s  process ,  while swapping . Kernel  in  System V  Unix ,  manipulates  the  region  tables , page  table , and pfdata  table  entries , by  incrementing  the  reference  count of  the  region  table of  shared  regions .

22 . What  are  the  requirements for  a  swapper  to  work ?

Ans : The  swapper  works  on  the  highest  scheduling  priority .  Firstly  it will look  for  any  sleeping  process ,  if  not  found  then  it  will  look  for the  ready - to - run  process  for  swapping .  But  the  major  requirement  for  the  swapper to  work  the  ready - to - run  process  must  be core-resident  for  atleast  2 seconds  before  swapping  out.

23 . What  is  Expansion  swap ?

Ans : At  the  time  when  any  process  requires  more  memory  than it  is currently  allocated ,  the  Kernel  performs  Expansion  swap . To  do  this  Kernel reserves  enough  space  in  the  swap  device. Then  the  address  translation

87

Page 88: Unix Manual

UNIX Lab Manual88

mapping  is  adjusted  for  the  new virtual address  space  but  the  physical memory  is  not  allocated. At last Kernel swaps the […]

24 . What  is  Fork  swap?

Ans : fork() is a system call to create a child process. When the parent process calls fork() system call, the child process is created and if there is short of memory then the child process is sent to the read-to-run state in the swap device, and return to the user state without swapping the parent process. […]

25 . What  are  the  entities  that  are  swapped  out  of  the  main  memory  while swapping  the process  out  of  the   main  memory?

Ans : All  memory  space  occupied  by  the  process ,  process’s  u-area , and Kernel  stack  are  swapped  out , theoretically .               Practically ,  if  the  process’s  u-area  contains  the  Address Translation Tables  for  the  process  then  Kernel  implementations  do  not swap  the  u-area .

26 . Is  the  Process  before  and  after  the  swap  are  the  same? Give  reason.

Ans : Process  before  swapping  is  residing  in  the  primary  memory  in  its original  form . The  regions  (text, data and stack)  may  not  be  occupied fully  by the  process ,  there  may  be  few  empty  slots  in  any  of  the regions  and  while swapping  Kernel  do  not  bother  about  the  empty  slots  while  swapping  the process  out  .

27 . What  are  the  events  done  by  the  Kernel  after  a  process  is being swapped  out  from  the main  memory?

Ans : When  Kernel  swaps  the  process  out  of  the  primary  memory ,  it performs  the  following:

88

Page 89: Unix Manual

UNIX Lab Manual89

                1 . Kernel  decrements  the  Reference  Count  of  each  region of the  process .  

               2 . If  the  reference  count  becomes  zero ,  swaps  the region  out  of  the  main  memory .               3 . Kernel  allocates  the  space  for  the  swapping  process  in the swap  device . Kernel  locks  the  other  swapping  process  while

28 . What  is  major  difference  between  the  Historic  Unix  and  the new  BSD release  of  Unix  System V  in terms  of  Memory Management?

Ans : Historic  Unix  uses  Swapping  –  entire  process  is  transferred  to  the main  memory  from  the  swap  device ,  

        whereas  the  Unix  System  V  uses Demand  Paging – only  the part of the  process  is  moved  to  the  main  memory .  Historic  Unix uses  one Swap  Device  and  Unix  System  V  allow  multiple  Swap Devices.

29 . What  is  an  advantage  of  executing  a process  in  background?

Ans : The  most  common  reason  to  put  a  process  in  the  background  is to allow  you  to  do  something  else  interactively  without  waiting  for  the process to  complete .  At  the  end  of  the  command  you  add  the  special background symbol , & . This  symbol  tells  your  shell  to  execute  the given  command  in the  background.                           Example: cp *.* / &

30 . What  Happens  when  you  execute  a  program ?

Ans : When  you  execute  a  program  on  your  UNIX  system ,  the  system creates  a  special  environment  for  that  program .  This  environment contains everything  needed  for  the  system  to  run  the  program  as  if  no other program  were  running  on  the  system . Each  process  has  process context , which  is  everything  that  is  unique  about  the  state  of  […]

89

Page 90: Unix Manual

UNIX Lab Manual90

31 . What  are  the  process  states  in  Unix?

Ans : As  a  process  executes  it  changes  state  according  to  its circumstances . Unix  processes  have  the  following  states :                Running : The  process  is  either running  or  it  is  ready  to  run .                 Waiting  : The  process  is  waiting  for  an  event  or  for  a  resource                Stopped : The  process  has  been  stopped ,  usually  by  receiving a signal.

32 . What  is  a  zombie?

Ans : When  a  program  forks  and  the  child  finishes  before  the  parent , the kernel  still  keeps  some  of  its  information  about  the  child  in  case the  parent might  need  it

                for  example ,  the  parent  may  need  to  check  the  child’s exit status . To  be  able  to  get  this  information , the  parent  calls `wait()‘;

33 . How  can  a  parent  and  child  process  communicate ?

Ans : A  parent  and  child  can  communicate  through  any  of  the  normal    inter - process  communication  schemes  (pipes, sockets, message queues, shared memory) , but  also  have  some  special  ways  to  communicate  that take advantage  of  their  relationship  as  a  parent  and  child . One  of  the most obvious  is  tha t the  parent  can  get  the  exit  status  of  the […]

34 . How  can  you  get/set  an  environment  variable  from  a program?

Ans : Getting  the  value  of  an  environment  variable  is  done  by  using `getenv()’.        Setting  the  value  of  an  environment  variable  is  done  by  using ` ‘putenv()’.

35 . Explain  fork()  system  call.

90

Page 91: Unix Manual

UNIX Lab Manual91

Ans : The  `fork()’   used  to  create  a  new  process  from  an  existing process .  The  new  process  is  called  the  child  process , and  the  existing process  is called  the  parent.  We  can  tell  which  is  which  by  checking the  return  value from  `fork()’.  The  parent  gets  the  child’s  pid returned to  him,

36 . What  are  various  IDs  associated  with  a  process?

Ans : Unix identifies each process with a unique integer called ProcessID. The process that executes the request for creation of a process is called the ‘parent process’ whose PID is ‘Parent Process ID’. Every process is associated with a particular user called the ‘owner’ who has privileges over the process.

37 . Brief  about  the  initial  process  sequence  while  the  system boots  up.

Ans : While booting, special process called the ’swapper’ or ’scheduler’ is created with Process-ID 0. The swapper manages memory allocation for processes and influences CPU allocation. The swapper inturn creates 3 children:

38 . What  is  a  shell?

Ans : A shell is an interactive user interface to an operating system services that allows an user to enter commands as character strings or through a graphical user interface.The shell converts them to system calls to the OS or forks off a process to execute the command.

39 .How  does  the  inode  map  to  data  block  of  a  file?

Ans : Inode has 13 block addresses.                       1 . The first 10 are direct block addresses of the first 10 data blocks in the file.                       2 . The 11th address points to a one-level index block. The 12th address points to a two-level  (double in-direction)  index block.

91

Page 92: Unix Manual

UNIX Lab Manual92

                      3 . The 13th address points to a three-leve l(triple in-direction) index block.                           

40 . Discuss  the  mount  and  unmount  system  calls

Ans : The privileged mount system call is used to attach a file system to a directory of another file system; the unmount system call detaches a file system. When you mount another file system on to your directory, you are essentially splicing one directory tree onto a branch in another directory tree. The first argument to […]

41 . How  do  you  create  special  files  like  named  pipes  and device  files?

Ans : The system call mknod creates special files in the following sequence.                      1. kernel assigns new inode,                       2. sets the file type to indicate that the file is a pipe, directory or special file,                       3. If it is a device file, it makes the other entries like major, minor device numbers.For example: If the device is a disk, major

42 . What  are  links  and  symbolic  links  in  UNIX  file  system?

Ans : A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers.Symbolic link ‘is’ a file that only contains the name of another file.Operation

43 . What  are  the  Unix  system  calls  for  I/O?

Ans :      open(pathname,flag,mode) - open file              creat(pathname,mode) - create file              close(filedes) - close an open file              read(filedes,buffer,bytes) - read data from an open file              write(filedes,buffer,bytes) - write data to an open file

92

Page 93: Unix Manual

UNIX Lab Manual93

             lseek(filedes,offset,from) - position an open file             dup(filedes) - duplicate an existing file descriptor             dup2(oldfd,newfd) - duplicate to a desired file descriptor              fcntl(filedes,cmd,arg) - change properties of an open file              ioctl(filedes,request,arg) - change the behaviour

44 .What  Happens  when  you  execute  a  program?

Ans : When you execute a program on your UNIX system, the system creates a special environment for that program. This environment contains everything needed for the system to run the program as if no other program were running on the system. Each process has process context, which is everything that is unique about the state of

45 . What  is  a  FIFO ?

Ans : FIFO are otherwise called as ‘named pipes’. FIFO (first-in-first-out) is a special file which is said to be data transient. Once data is read from named pipe, it cannot be read again.Also, data can be read only in the order written. It is used in interprocess communication where a process writes to one end of

46 . What  is  ‘inode’?

Ans : All UNIX files have its description stored in a structure called ‘inode’. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers

47 .  How  are  devices  represented  in  UNIX ?

Ans : All devices are represented by files called special files that are located in/dev directory. Thus, device files and other files are named and accessed in the same way. A ‘regular file’ is just an ordinary data file in the disk. A ‘block special file’ represents a device with characteristics similar to a disk (data transfer

93

Page 94: Unix Manual

UNIX Lab Manual94

48 . Brief  about  the  directory  representation  in  UNIX

Ans : A Unix directory is a file containing a correspondence between filenames and inodes. A directory is a special file that the kernel maintains. Only kernel modifies directories, but processes can read directories. The contents of a directory are a list of filename and inode number pairs. When new directories are created, kernel makes two entries […]

49 . How is the command “$cat file2 “ different from “$cat >file2

Ans : The Commond $cat file in unix is used to display the content of the file and where as commond $cat >> file is to append the text to the end of the file without overwritting the information of the file. Incase if the file does not exist in the directory the commond will create a newfile in file system.

$cat >file means to create a new file $cat file means to open an existing file.

cat > file it means creating file for file cat file it means used to display the file content .

The Commond $cat file in unix is used to display the content of the file and where as commond $cat >> file is to append the text to the end of the file without overwritting the information of the file. Incase if the file does not exist in the directory the commond will create a newfile in file system.

$cat >file means to create a new file $cat file means to open an existing file.

cat > file it means creating file for file cat file it means used to display the file content

50 . Explain the steps that a shell follows while processing a command.

Ans : When processing a command the searchs for the utility for the command in the directories specified in the PATH varible and it in invokes that utility. That utility will execute the command with help of kernel and the output is given to shell. And then the displays out put to the user.

94

Page 95: Unix Manual

UNIX Lab Manual95

52. Which command is used to delete all files in the current directory and all its sub-directories

Ans : #rm -fr <Directory name>

# rm -rf *

53 . What is the use of the command "ls –x chapter[1-5]"

Ans : Yes you are correct. It stands for listing the files Chapter with suffix 1 to 5 but it will display the files in columns as with-x option.

54 . How does the kernel differentiate device files and ordinary files?

Ans : Device filles are of 2 types --- charcater device file and block device file

type field in the file's inode structure

b--- block device file

c--- character device file

55. How to switch to a supe user status to gain privileges?

Ans : Use ‘su’ command. The system asks for password and when valid entry is made the user gains super user (admin) privileges

56 . What are shell variables?

Ans : Shell variables are system environment variables.They include

TERM,SHELL, MAIL

the output of the shell variable we can see by typing the command

$>echo $TERM

95

Page 96: Unix Manual

UNIX Lab Manual96

57 . What is redirection?

Ans : Redirection is a feature in Unix where the data from the standard out put or a file,so on. can be redirected i.e divert to a file or a program and vice versa. > -- out put redirection

>> -- out put redirectin(appending at the last)

< -- input redirection

58 . How to terminate a process which is running and the specialty on command kill 0 ?

Ans : With the help of kill command we can terminate the process. Syntax: kill pid Kill 0 - kills all processes in your system except the login shell.

59 . How to sfind free space in unix/linux?

Ans : Df and du commands are used for checking free space on disk .df -h or df -Humanreadable gives human readable format of free space

60 . What is the difference between soft link and hard link in unix operating system ?

Ans :

Hard Links :

1. All Links have same inode number.

2 .ls -l command shows all the links with the link column(Second) shows No. of links.

96

Page 97: Unix Manual

UNIX Lab Manual97

3. Links have actual file contents

4.Removing any link ,just reduces the link count , but doesn't affect other links.

Soft Links(Symbolic Links) :

1.Links have different inode numbers.

2. ls -l command shows all links with second column value 1 and the link points to original file.

3. Link has the path for original file and not the contents.

4.Removing soft link doesn't affect anything but removing original file ,the link becomes "dangling" link which points to nonexistant file.

61. how to concatenate two FILES ?

Ans : for concatenating two FILES use ‘cat’ command

62 . Explain UNIX kernel .

Ans : UNIX kernel is heart of the OS.UNIX kernel is loaded first when UNIX system is booted.It handles allocation of devices,CPU,memory.

63 . How many prompts are available in a UNIX system

Ans : Unix/ Linux Supports four Prompts PS1, PS2, PS3, PS4 #,@,$,% are 4 prompts

REFERENCES:

Books:

1) Unix and shell Programming –A text book, B.A. Forouzan & R.F. Giberg, Thomson

97

Page 98: Unix Manual

UNIX Lab Manual98

2)Unix concepts and applications, Fourth Edition, Sumitabha Das, TMH.

3)Unix for programmers and users, 3rd edition, Gaham Glass & K. Ables, pearson education..

5)Beginning shell scripting, E. Foster – Johnson & other, Wile Y- India.

98