Unix Manual

Share Embed Donate


Short Description

Download Unix Manual...

Description

1

UNIX Lab Manual

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.APPARAO Assistant Professor Head Of The Department APPARAO GODI Department of CSE Assistant Professor GITAM Institute of Technology VENKATESWARLU K GITAM UNIVERSITY Assistant Professor DIVAKAR A Assistant Professor ****************************************************************************************** 1

2

UNIX Lab Manual

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

5

Week wise exercises

8 9

6

Frequently used UNIX commands

7

Vi

8

About shell

9

Editor

28

34 40

Introduction to shell programming 44

10

Viva Questions and Answers

11

References

83 98

2

3

UNIX Lab Manual

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

4

UNIX Lab Manual

INTRODUCTION ABOUT LAB

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

: :

Intel® Core™2 duo CPU

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

5

UNIX Lab Manual

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 5

6

UNIX Lab Manual 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

How to Run Shell Scripts

There are two ways you can execute your shell scripts. Once you have created a script file: Method 1 Pass 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 show Here is the date and time Sat 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 6

7

UNIX Lab Manual echo Here is the date and time date

Step 2 : Make the file executable $ chmod u+x script_file $ chmod u+x show Step 3 : To run the script, just type the filename $ show Here is the date and time Sat 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

8

UNIX Lab Manual

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 8

9

UNIX Lab Manual A ) Sample program B ) Expressions C ) Decision making

Week Wise Exercises Week1 Practice Session 1.Log in to the system 2.Practice the following basic commands Command Name date

description

Synopsis: date [-options] [+format] Diplays the time and date 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 passwd Synopsis: passwd Changes the user password Synopsis :man commandname man Display manual of any command name tty Synopsis: tty Displays name of a terminal. script Synopsis: sript [filename] Records interactive session. clear Synopsis: clear Clears monitor screen. whoami Synopsis: whoami displays user information bc Synopsis: bc Calculator.

Week1 exercises: 1. Change the password. 2. Load your work into some file. 9

important options u

H, u

a, g a,n, r,s,

10

UNIX Lab Manual 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.

Week2 Practice Session 1. Log in to the system 2. Practice the following file/directory handling utilities with options

10

11

COMMAND Synopsis and discription UNIX Lab Manual NAME Synopsis: file 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. 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. Synopsis : cp[-options] source destination Copies files or directories from source to the cp destination. mv Synopsis: mv[-options] source destination Moves a files or directory from source to destination ls Synopsis: ls[-options][pathname] Lists all the contents of the directory. find Synopsis: find pathname criteria Finds a file or directory based on criteria. head Synopsis: head[-options][file-list] Displays lines at the beginning of a file (default is 10 lines). tail Synopsis :tail[-options][file-list] Displays lines at the end of a file (default is 10 lines). more Synopsis: more[-options][file-list] Displays the contents of a file one screenful at a time rm Synopsis: rm[options]list Removes ( deletes) files or directories mkdir Synopsis: mkdir [-options] directory-list Creates one or more directories Synopsis: rmdir directory-list Removes ( deletes) directories rmdir Synopsis: cd[directory] Changes the current directory defined by the cd 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 11 in a file.

Important option

n,s,t,u,v,e

R

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

r,s,

-N -N,+N,b,c,l,r C,d,f,l,r,s, u,w,lines,+nmbr f,i,r, P,m

a, g

12

UNIX Lab Manual

Week2 exercises: 1. Create two files and concatenate into file using cat. 2. Remove directory without deleting files in directory 3. Check the group permissions of any file 4. 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 1.Login into system. 2.Execute the mail commands with options. Command Talk

Description Synopsis:talk user-id [terminal] Used to create a chatting environment between wo users that are logged into the same or a 12

Options

13

Write Mail

mesg

wall

UNIX Lab Manual different system. Synopsis:write user-id [terminal] Used to send a meesage to a receiver logged into the same or a different system from the sender. 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. Synopsis: mesg y/n Allows and disallows messges coming from other user 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 others 4. reply to the message 5. Use talk command to exchange messages. 6. Write command to send message to your friend.. 7. Find the path of your mbox 8.broadcast ”hai” to all

Week 4 Practice Session 1. Login into the system. 2. Execute Grant and Revoke commands for user group and other. Command Chmod Chown

Description Synopsis:chmod[-option]mode list Sets or changes the permission of a list of files or directories. Synopsis: chown[-option] owner [:group] 13

Options R R

14

UNIX Lab Manual list Changes the owner (and the group associated to) a list of files or directories. Synopsis:chgrp[-option] group list Changes a group associated with a list of files or directories. Synopsis:umask[mask] Displays or sets the default pemission for newly created files or directories. Synopsis:groups [user-id] Displays the user’s group.

Chgrp Umask Groups

R

3.Execute Piping commands Use of Redirection mask Input 0 Output 1 Error w

Tee

< >

file 1

2 2 2

> file2 > 1 file2 >> file | who|tee whooct2

Week 4 Exercises: 1. Change the permission of any file (add execute permission to group) a. Using symbolic form b. 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 file 5.check the group id and users logged in 14

15

UNIX Lab Manual 6. 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 e grep

fgrep

grep

Description Synopsis: egrep[options]’regexpr’.[filelist] Selects lines that match the regular expression. Synopsis:fgrep[options]’string’[file-list] Selects lines that match the string. Synopsis:grep[options]’regexpr’[file-list] Selects lines match the regular expression.

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

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

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

15

16

UNIX Lab Manual 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 -l c.tr “ABC” “***” file1 d.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 1. Log in to the system 2. Practice the following sed commands Category Line Number

Command =

Description Writes the line number 16

17

UNIX Lab Manual Modify

Substitute

I a c d D s

Inserts Text Appends Text Changes text Deletes the pattern space Deletes the first line of pattern space Substitutes a pattern with a replacement string

Transform

y

Transforms a set of characters to another set

Input/Output

n N

Reads the next line into the pattern Space Appends the next line in the file to the contents of the pattern space Sends the content of the pattern space to the standard output Sends only the first line of the pattern space to the standard output List the contents of the pattern space with nonprinting characters represented by their ASCII codes

p P l

Files

r w

Branch

: b t

Hold Space

h H g G x

Quit

q

Reads the contents of the file and appends to the pattern space Writes the contents pf the pattern space to a file Labels a line to be used by branch(b) and test(t) commands Branches unconditionally to the label. Branches on successful substitution Copies the contents of the pattern space to the hold space Append the contents of the pattern space to the whole space Copies the contents of the hold space to the pattern space Appends the contents of the hold space to the pattern space Swaps the contents of the pattern space with the contents of the hold space Stops processing the input file

Week 6 Exercises: 1. Show the result of the sed command Sed “s/bc*./z/” On the following file : 17

18

UNIX Lab Manual 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 line in a file .

character in each

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

19

UNIX Lab Manual 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 session 1. Write shell script for reading two values and display them Sol: echo "enter the values of a and b" read a b echo the values are a=$a b=$b output: 19

20

UNIX Lab Manual [[email protected] ~]$ sh s.sh enter the values of a and b 345 789 the 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 n ls $n |wc -w exit 0 output: [[email protected] ~]$ sh s1.sh enter the directory name /home/cse3c23 2 [[email protected] ~]$ ls s1.sh s.sh 3. Write a shell script to read two numbers? Sol: echo enter the values of a b and c read a b c echo the value of a=$a echo the value of b=$b echo the value of c=$c d=`expr $a + $b + $c` echo the result is d=$d output: [[email protected] ~]$ sh add.sh enter the values of a b and c 23 56 89 the value of a=23 the value of b=56 the value of c=89 the result is d=168

week 7 exercises 1. Write a shell script to find G.C.D. of two numbers 2. 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 1.write a shell script to find an Armstrong number Armstrong Number echo enter the number 20

21

UNIX Lab Manual read n temp=$n sum=0 while [ $n - gt 0 ] do r=`expr $n % 10` sum=`expr $sum + \( $r \* $r \* $r \)` n=`expr $n / 10` done if [ $temp -eq $sum ] then echo $temp is armstrong else echo $temp is not armstrong fi exit 0 Output 1: [[email protected] ~]$ sh a.sh enter the number 153 153 is armstrong Try this Output 2: [[email protected] ~]$ sh -x a.sh --------------------------------------------------------------------------------------------------------------------FACTORIAL 2.write a shell script to find factorial of a number FACTORIAL echo enter a number read n sum=1 while [ $n -gt 1 ] do sum=`expr $sum \* $n` n=`expr $n - 1` done echo $sum exit 0 Output 1: [[email protected] ~]$ sh n.sh enter a number 6 720 Try this Output 2: 21

22

UNIX Lab Manual [[email protected] ~]$ sh -x n.sh --------------------------------------------------------------------------------------------------------------------LARGEST NO 3.write a shell script to find largest number for three numbers passed with command LARGEST NUMBER if [ $1 -gt $2 && $1 –gt $3 ] then x=$1 elif [ $2 -gt $3 ] then x=$2 else x=$3 fi echo largest number is $x exit 0 Output 1: [[email protected] ~]$ sh g.sh 12 34 45 largest number is 45 Output 2: [[email protected] ~]$ sh -x g.sh 67 23 45 + '[' 67 -gt 23 ']' + x=67 + echo largest number is 67 largest number is 67 + exit 0 --------------------------------------------------------------------------------------------------------------------PERFECT NO 4.write a shell script to find a perfect number PERFECT NUMBER echo enter a number read no i=1 ans=0 while [ $i -le `expr $no / 2` ] do if [ `expr $no % $i` -eq 0 ] then ans=`expr $ans + $i` fi i=`expr $i + 1` done 22

23

UNIX Lab Manual if [ $no -eq $ans ] then echo $no is perfect else echo $no is not perfect fi Output 1: [[email protected] ~]$ sh p.sh enter a number 34 34 is not perfect Try this Output 2: [[email protected] ~]$ 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 9 Practice section REVERSE 23

24

UNIX Lab Manual 1.write a shell script to find reverse of a number REVERSE echo enter a num read num rev=0 while [ $num -gt 0 ] do k=`expr $num \% 10` l=`expr $rev \* 10` rev=`expr $l + $k` num=`expr $num / 10` done echo reverse number is $rev exit 0 Output 1: [[email protected] ~]$ sh r.sh enter a num 12345 reverse number is 54321 Output 2: try this [[email protected] ~]$ sh -x r.sh --------------------------------------------------------------------------------------------------------------------EVEN AND ODD 2.write a shell script to even or odd EVEN OR ODD echo enter a number read n i=1 while [ $i -le $n ] do echo enter term read x if [ `expr $x \% 2` -eq 0 ] then echo $x is even else echo $x is odd fi i=`expr $i + 1` done Output 1: [[email protected] ~]$ sh eo.sh enter a number 4 24

25

UNIX Lab Manual enter term 3 3 is odd enter term 2 2 is even enter term 7 7 is odd enter term 8 8 is even

Output 2: try this [[email protected] ~]$ sh -x eo.sh --------------------------------------------------------------------------------------------------------------------FIBONACCI 3.write a shell script to display Fibonacci series FIBONACCI echo enter the number of terms read n f1=0 f2=1 i=1 echo $f1 echo $f2 while [ $i -le $n ] do f3=`expr $f1 + $f2` f1=$f2 f2=$f3 i=`expr $i + 1` echo $f3 done exit 0 Output 1: [[email protected] ~]$ sh fb.sh enter the number of terms 5 0 1 1 2 3 5 8 25

26

UNIX Lab Manual Output 2:try this [[email protected] ~]$ sh -x fb.sh --------------------------------------------------------------------------------------------------------------------PALINDROME 4.write a shell script to check palindrome PALINDROME echo enter a num read num rev=0 temp=$num while [ $num -gt 0 ] do k=`expr $num \% 10` l=`expr $rev \* 10` rev=`expr $l + $k` num=`expr $num / 10` done if [ $rev -eq $temp ] then echo $temp is a palindrome else echo $temp is not a palindrome fi exit 0 Output 1: [[email protected] ~]$ sh fbb.sh enter a num 234 234 is not a palindrome Output 2: try this [[email protected] ~]$ sh fbb.sh

Week 9 exercises 1. Write a shell script that computes the gross salary of a employee according To the following rules a) if basic salary is < 1500 then HRA=10% of the basic salary and DA=90% of basic b) if basic salary is >=1500 theen HRA=Rs 500 and DA=98% of basic The basic salary is entered interactively through the keyboard 2. Write an interactive shell program for copying, removing, renaming & linking 3. Write a shell script that accepts one or more file name as arguments and converts all of them to uppercase, provided they exist in the current directory 4. Verify executable files in your directory

Week 10 exercises 26

27

UNIX Lab Manual 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). 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 output should 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

27

28

UNIX Lab Manual

Frequently used unix commands

UNIX Commands Command . (dot) : (colon) Alias

Awk Basename Bash Bc Bg break breaksw cal case

Description Synopsis:. Command Reads file from the current shell. Synopsis: (null command) Does nothing (a placeholder). The exit status is always true. Synopsis: alias name definition alias [name=definition] #Korn and Bash alias[name definition] #C shell Lists existing aliases or creates new alias for a command. Synopsis: awk [options] script [file-list] Selects and processes specified lines in the input file. Synopsis: basename pathname [argument] Extracts base name or extension of a path name. Synopsis: bash Creates a new bash shell. Synopsis: bc Calculator. Synopsis: bg [job_number] Moves a suspended job to the background. Synopsis: break Forces a loop to terminate. Synopsis: breaksw Terminates execution of case commands. Synopsis: cal [[month] year] Displays the calendar for a month or a year. Synopsis: case string in pat) command (s);; pat) command (s);; ... esac Creates a multiway selection.

28

Options

-F, -f

29

UNIX Lab Manual

Command

Description

Options

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 list Changes a group associated with a list of files or directories.

R

Chmod

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

R

Chown

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

R

Clear

Synopsis: clear Clears monitor screen

Cmp

Synopsis: cmp [-options] file1 file2 Determines if files are identical

Comm

Synopsis: comm file1 file2 Displays common lines in two files

continue

Synopsis: continue Continues with the next iteration of the loop

Cp

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

Csh

Synopsis: csh Creates a new C shell Terminates (aborts) a foreground job

Ctrl+c

29

l ,s

30

Ctrl+z

UNIX Lab Manual Stops-(suspends) a foreground job

Command

Description

Cut

Synopsis: cut [-options] [file-list] Splits files into columns Synopsis: date [-options] [+format] Diplays the time and date Synopsis: diff [-options] file1 file2 diff [-options] file dir diff [-options] dir file2 diff [-options] dir1 dir2 Identifies differences between two files Synopsis: dirname pathname Extracts the directory name of a pathname

Date Diff

dirname Grep Groups Head History If-thenElse

jobs kill ksh Let

Options

Synopsis: grep [-options] ‘regexpr’ [file-list] Selects lines that makes the regular expression Synopsis: groups [user id] Displays the user’s group Synopsis: head [-options] [file-list] Displays lines at the beginning of a file (default is at 10 lines) Synopsis: history –n l-rl command_name Displays contents of the command history file Synopsis: if command Then ......... Else ......... Fi Create a two way selection Synopsis: jobs Displays the list of active objects Synopsis: kill [job_number] Kills a job Synopsis: ksh Creates a new Korn shell Synopsis: let variable=mathematical expression 30

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

31

S,i,f

Lpr

UNIX Lab Manual Evaluates a mathematical expression Synopsis: ln [-options] source link Links the source to destination Synopsis: lpr [-options] [file-list]

Command

Description

Options

Ls

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

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

Mail

Synopsis: mail [receiver-list] Used to read or send mail. When it is used without Argument ,it is in the read mode. When an argument is used ,it is in the send mode Synopsis: man command-name Displays online documentation for the command Synopsis: mkdir [-options] directory-list Creates one or more directories

Ln

Man Mkdir

31

p

P,m

32

UNIX Lab Manual More

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

Mv

Synopsis: mv [-options] source destination Moves a file or directory from source to destination or Renames a file or directory. Synopsis: onintr [label] Runs a command when a signal received. Synopsis: passwd Changes the user password. Synopsis: paste [-options] [file-list] Combines lines of files into one single line. Synopsis: print argument list Displays contents of a variable or a string Synopsis: ps Displays information about the active processes. Synopsis: pwd Displays the absolute pathname of the current (working) directory. Synopsis: r line [ -line] command_name Reexecutes (redo) specified command in history file . Synopsis: read [options] variable-list Reads values and stores them in variables.

onintr passwd paste print ps pwd r read

Command

Description

readonly

Synopsis: readonly variable –list Makes the variables read only. Synopsis: return [expression] Returns from function. Synopsis: rm [-options] list Removes (deletes) files or directories. Synopsis: rmdir directory-list Removes (deletes) directories. Synopsis: script [filename] Records interactive session. Synopsis: sed [-options] script [file-list] Edits specified lines in the input files and processes Them.

return rm rmdir script sed

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

d

Options

32

f, i, r

A n, e, f

33

UNIX Lab Manual

Select

Set

Setenv

Shift Sleep Sort

Source Stop Sty Switch Tall Talk Tee

Synopsis: select variable in list do ..... done Creates a menu environment. Synopsis: set expression set var=value #C shell set –o option #Korn and Bash set +o option #Korn and Bash Sets 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. Synopsis: setenv var = value Setenv variable value Defines an exportable variable. In C shell,sets a value for an environmental variable. Synopsis: shift expression Shifts the parameters to the left. Synopsis: sleep seconds Sleeps for a number of seconds Synopsis: sort [-options] [field-specifiers] [file-list] Sorts or merges files. Synopsis: source command Executes command in current shell. Synopsis: stop [job_number] Stops (suspends) a background job. Synopsis: stty Sets or unsets selected terminal input/output options. Synopsis: tail user-id [terminal] Used to create a chatting environment between two users that are logged into the same or a different system. Synopsis: tail [-options] [file] Displays lines at the end of a file(default is 10 lines). Synopsis: talk user-id [terminal] Used to create a chatting environment between two users that are logged into the same or a different system. Synopsis: tee [-option] file-list 33 output and at the same time Copies standard input to standard copies to one or more files.

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

a, g

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

a

34

UNIX Lab Manual

telnet test tr trap tty typeset

umask unalias

uname uniq unset unsetenv until

vi

Synopsis: telnet Connects the user to the remote computer defined by the argument(domain_name). Synopsis: test arguments Evaluates a relational,logical,or file expression. Synopsis: tr [-options] [string1] [string2] Translates (replaces) a set of characters (string1) with another set (string2). Synopsis: trap “action” signals Runs a command when a signal is received. Synopsis: tty Displays name of a terminal. Synopsis: typeset –attribute variable typeset +attribute variable Associates (-) and unassociates (+) data attributes,such as numeric and justification,to a variable. Synopsis: umask [mask] Displays or sets the default permission for newly created files or directories. Synopsis: unalias alias-list Removes some or all aliases. Synopsis: uname Displays system data. Synopsis: unique [-options] [input_file] Displays the unique lines in a file. Synopsis: unset variable unset option #Cshell Unsets the value of a variable or unsets an option. Synopsis: unsetenv variable In C shell,unsets the value of an environmental variable. Synopsis: until command do body done Repeats the body until the command is successful(exit status 0). Synopsis: vi [-options] [file name] Used to create a new file or edit an existing file. 34

c,d,s

A (korn and bash) a,n, r,s,sr u,c,d

R

35

UNIX Lab Manual

Wc while

who whoami write

Synopsis: wc[options] [file-list] Displays the number of lines,words,and characters in a file Synopsis: while(expression) body end Repeats the body while the expression is successful (exit status 0). Synopsis: who [options][am i] Displays all users currently logged into the system. Synopsis: whoami Displays the id of the user. Synopsis: write user-id [terminal] Used to send a message to a receiver logged into the same or a different system from the sender.

35

c, l, w

H, u

36

UNIX Lab Manual

Vi editor What are Different Editors

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

37

UNIX Lab Manual 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 (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 vi To use vi on a file, type in vi filename. If the file named filename exists, then the first page (or screen) of the file will be displayed; if the file does not exist, then an empty file and screen are created into which you may enter text.

* vi filename vi -r filename

edit filename starting at line 1 recover filename that was being edited when system crashed

To Exit vi Usually the new or modified file is saved when you leave vi. However, it is also possible to quit vi without saving the file. Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This type of command is completed by hitting the (or ) key. * :x :wq :q * :q!

quit vi, writing out modified file to file named in original invocation quit vi, writing out modified file to file named in original invocation quit (or exit) vi quit vi even though latest changes have not been saved for this vi call

Moving the Cursor

37

38

UNIX Lab Manual 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 key should be held down while the letter key is pressed. * j or [or down-arrow] * k [or up-arrow] * h or [or left-arrow] * l or [or right-arrow] * 0 (zero) * $ w b :0 or 1G :n or nG :$ or G

move cursor down one line move cursor up one line move cursor left one character move cursor right one character move cursor to start of current line (the one with the cursor) move cursor to end of current line move cursor to beginning of next word move cursor back to beginning of preceding word move cursor to first line in file move cursor to line n 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 ^b ^d ^u ^l ^r

move forward one screen move backward one screen move down (forward) one half screen move up (back) one half screen redraws the screen redraws the screen, removing deleted lines

Adding, Changing, and Deleting Text 38

39

UNIX Lab Manual 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 Text The following commands allow you to insert and add text. Each of these commands puts the vi editor into insert mode; thus, the key must be pressed to terminate the entry of text and to put the vi editor back into command mode. * i I * a A * o

insert text before cursor, until hit insert text at beginning of current line, until hit append text after cursor, until hit append text to end of current line, until hit open and put text in a new line below current line, until hit * O open and put text in a new line above current line, until hit

Changing Text The following commands allow you to modify text. * r R

replace single character under cursor (no needed) replace characters, starting with current cursor position, until hit cw change the current word with new text, starting with the character under cursor, until hit cNw change N words beginning with character under cursor, until hit; e.g., c5w changes 5 words C change (replace) the characters in the current line, until hit cc change (replace) the entire current line, stopping when is hit Ncc or cNc change (replace) the next N lines, starting with the current line, stopping when is hit

Deleting Text The following commands allow you to delete text. 39

40

UNIX Lab Manual * x Nx dw dNw

delete single character under cursor delete N characters, starting with character under cursor delete the single word beginning with character under cursor 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 Text The 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

Searching Text A 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 ?string n N

search forward for occurrence of string in text search backward for occurrence of string in text move to next occurrence of search string move to next occurrence of search string in opposite direction

Determining Line Numbers Being able to determine the line number of the current line or the total number of lines in the file being edited is sometimes useful. :.= := ^g

returns line number of current line at bottom of screen returns the total number of lines at bottom of screen 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 40

41

UNIX Lab Manual These commands permit you to input and output files other than the named file with which you are currently working. :r filename

:w :w newfile :12,35w smallfile :w! prevfile

read file named filename and insert after current line (the line with cursor) write current contents to file named in original vi call write current contents to a new file named newfile write the contents of the lines numbered 12 through 35 to a new file named smallfile write current contents over a pre-existing file named prevfile

Scrolling through a file The 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 ctrl-b ctrl-d ctrl-u ctrl-e ctrl-y

Scroll forward a page Scroll back a page Scroll forward half a page Scroll back half a page Scroll forward a line Scroll back a line

41

42

UNIX Lab Manual

The Shell Whenever 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 42

43

UNIX Lab Manual 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)

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

43

44

UNIX Lab Manual

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

> 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 ________________________________________________________ 44

45

UNIX Lab Manual

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

Yes

Yes

Yes

Yes

No

________________________________________________________ * not the default setting for this shell

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.

45

46

UNIX Lab Manual

> 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

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 46

47

UNIX Lab Manual 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

System Variable BASH_VERSION=1.14.7(1) COLUMNS=80 HOME=/home/vivek LINES=25 LOGNAME=students OSTYPE=Linux PATH=/usr/bin:/sbin:/bin:/usr/sbin PS1=[\[email protected]\h \W]\$ PWD=/home/students/Common SHELL=/bin/bash USERNAME=vivek

Meaning Our shell version name No. of columns for our screen Our home directory No. of columns for our screen Our logging name Our o/s type : -) Our path settings Our prompt settings Our current working directory Our shell name User name who is currently login to this PC

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.

47

48

UNIX Lab Manual 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

$ 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

48

49

UNIX Lab Manual following variable declaration there will be no error $ no=10 But here there will be problem for following $ no

=10

$ no= $ no

10 =

10

(3) Variables are case-sensitive, just like filename in Linux. For e.g. $ no=10 $ No=11 $ NO=20 $ nO=2 Above all are different variable name, so to print value 20 we have to use $ echo $NO and Not any of the following $ echo $no

# will print 10 but not 20

$ echo $No

# will print 11 but not 20

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

49

50

UNIX Lab Manual 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 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

50

51

UNIX Lab Manual $ 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 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

51

52

UNIX Lab Manual $ 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 # 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 52

53

UNIX Lab Manual echo "Message" echo "Message variable1, variable2....variableN"

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 53

54

UNIX Lab Manual 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 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

54

55

UNIX Lab Manual 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

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

Explanation Go to your home directory

55

56

UNIX Lab Manual 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 $ first

copy your script 'first' to your bin directory 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...] 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

56

57

UNIX Lab Manual \\ 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" 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 57

58

UNIX Lab Manual $ 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 $ 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

58

59

UNIX Lab Manual 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

cp

2

y and y.bak

mv tail

2

y.bak and y.okay

2

-10 and myf

mail

1

sort

3

date

0

clear

0

raj -r, -n, and myf

NOTE: $# holds number of arguments specified on command line. and $* or [email protected] refer to all

59

60

UNIX Lab Manual 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 $ 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 60

61

UNIX Lab Manual 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

$0

$#

sum

2

math

3

d

0

bp

cal

$0

$1

$2

$3 $4 11

4

3

ls

Actual Argument ($1,..$9)

-

7

-5 myf +20 1

*

0

61

20

62

UNIX Lab Manual 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 $ 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 62

63

UNIX Lab Manual 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 $? $ wildwest canwork? $ echo $? $ date $ echo $? $ echon $?

63

64

UNIX Lab Manual $ 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) 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 64

65

UNIX Lab Manual 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

Is 1 is less than 2

Yes

1

1,2 3+6 3 * 65 a5 c > 5 + 30 -1 Type following command (assumes you have file called foo) $ cat foo $ 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 # 66

67

UNIX Lab Manual #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 1) Create following script cat > trmif # # Script to test rm command and exist status # 67

68

UNIX Lab Manual 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 output.

bar what will be

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 # # Script to see whether argument is positive # if test $1 -gt 0

68

69

UNIX Lab Manual 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 3.Character strings For Mathematics use following operator in Shell Script Math- ematical Normal Arithmetical/

69

70

UNIX Lab Manual 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

-ne

is not equal to

-lt

is less than

5 == 6

if test 5 -eq 6

if expr [ 5 -eq 6 ]

5 != 6

if test 5 -ne 6

if expr [ 5 -ne 6 ]

5= 6

if test 5 -ge 6

equal to

NOTE: == is equal, != is not equal. For string Comparisons use Operator

Meaning

70

if expr [ 5 -ge 6 ]

71

UNIX Lab Manual 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. Syntax: if condition then

71

72

UNIX Lab Manual 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 fi if test $1 -gt 0

72

73

UNIX Lab Manual 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" |

|

|

|

1

2

1 will print Name of script

73

74

UNIX Lab Manual 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 fi

74

75

UNIX Lab Manual 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

then

echo "$1 is zero" else

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

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 Run it as,

75

76

UNIX Lab Manual $ 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

76

77

UNIX Lab Manual 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 ]

77

78

UNIX Lab Manual 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

78

79

UNIX Lab Manual while [ $i -le 10 ]

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

79

80

UNIX Lab Manual 7 * 10 = 70, Here each time value of variable n is 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

80

81

UNIX Lab Manual ... .. 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

81

82

UNIX Lab Manual # i.e. -z $1 is defined and it is NULL # # if no command line arg if [ -z $1 ] then rental="*** Unknown vehicle ***" elif [ -n $1 ] then # otherwise make first arg as rental rental=$1 fi case $rental in "car") echo "For $rental Rs.20 per k/m";; "van") echo "For $rental Rs.10 per k/m";; "jeep") echo "For $rental Rs.5 per k/m";; "bicycle") echo "For $rental 20 paisa per k/m";; *) echo "Sorry, I can not gat a $rental for you";; esac Save it by pressing CTRL+D $ chmod +x car $ car van $ car car $ car Maruti-800 Here first we will check, that if $1(first command line argument) is not given set value of rental

82

83

UNIX Lab Manual 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 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.

83

84

UNIX Lab Manual (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. 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/ash

/bin/basename

/bin/ash.static

/bin/bash

/bin/bsh

/bin/chmod

/bin/cat

/bin/cp

/bin/chown

/bin/chgrp

/bin/cpio

/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/red

/bin/sayHello

/bin/stty

/bin/umount

84

/bin/wcomp /bin/xconf

85

UNIX Lab Manual /bin/remadmin /bin/rm

/bin/sed

/bin/su

/bin/setserial

/bin/sync

/bin/rmdir

/bin/sfxload

/bin/tar

/bin/rpm

/bin/sh

/bin/tcsh

/bin/uname

/bin/ypdomainname

/bin/userconf /bin/zcat /bin/usleep /bin/vi

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

85

86

UNIX Lab Manual

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?

86

87

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

6 . List the system calls used for process management:

Ans : System calls fork() exec()

Description To create a new process To execute a new program in a process

7 . How do you change File Access Permissions? Ans : Every 1. 2. 3.

file has following attributes: owner’s user ID ( 16 bit integer ) owner’s group ID ( 16 bit integer ) 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 87

88

UNIX Lab Manual 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? 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.

88

89

UNIX Lab Manual 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. 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 : 89

90

UNIX Lab Manual 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? 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 ?

90

91

UNIX Lab Manual 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 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. 91

92

UNIX Lab Manual 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: 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 92

93

UNIX Lab Manual 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 […]

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 […] 93

94

UNIX Lab Manual 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. 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?

94

95

UNIX Lab Manual 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. 3 . The 13th address points to a three-leve l(triple indirection) 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?

95

96

UNIX Lab Manual 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 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’?

96

97

UNIX Lab Manual 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 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 97

98

UNIX Lab Manual 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. 52. Which command is used to delete all files in the current directory and all its sub-directories Ans : #rm -fr # 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 98

99

UNIX Lab Manual 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 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? 99

10 0

UNIX Lab Manual 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. 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. 100

10 1

UNIX Lab Manual

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

101

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF