sap4help@gmail.com +91 8956877466
This website is always under updation with new contents
Unit - V
Unit I
Unit II
Unit III
Unit IV
Unit V
Q1) Explain with example and syntax, if -then-else- if command used in Unix Shell scripts.
Ans: The if condition allow certain conditions to be tested for and then appropriate actions to be invoked depending on the result.
The syntax for two different shells are given as follows:
Bourne shell:
Ifthen
	[actions-----]
Elif [actions-------]
	Then [actions---------]
Else
	[actions---------]
Fi
	Syntax in c shell: 
	If  Then
		[actions]
	Else
		[actions]
Fi
The argument allows the user to specify the user to specify one or more conditions to be attached to the if statement.
If the condition is true then the actions following the if statements are carried out,
otherwise the actions following the elif(elseif) component are executed.
This allows if statement to be nested which makes the selection process more powerful statements are used to be execute the statements following each elif because they also follow the .
The elif and else components are optional and can be removed if desired.
The fi statement closes the whole construct and must be included.
The final else statement is used when a condition is not satisfied, to execute the necessary actions in this situation.
Note that if a condition is met using the elif structure then the else statement will be skipped and the actions beneath it will not be performed.
The [actions----] themselves can be shell commands or further (‘nested’) if then structures.
Examples:
If [‘grep John/etc/passwd’] then
Echo ‘john exists in the /etc/passwd file.’
Else
Echo ‘john doesnot exist in th etc/passwd file’
Fi
This construct uses an if statement to detect the presence of the user named John in th etc/passwd file.
Command substitution is used in the test condition.
Grep returns a true or false exit status depending on whether it found the search pattern in the named file.
Grave accenst (‘) must be used in this way when using shell commands as test condition.
Q2) What are interrupts? How interrupts are handled in Unix operating system.

Ans: During the time that a program is executing you may want to disable or even process any interrupt signals that may occur.
The trap command allows many signals to be caught and evaluated, whereupon a series of actions can be taken.
An example of a common interrupt that can be scanned for is SIGINT generated by pressing < the interrupt key.
Trap allows us to set up a sequence of commands that are to be trapped.
The commands to be executed, when the particular signal has been detected, may need to be quoted because they are included as a signal argument.
Multiple commands can be inserted using; character and by bracketing the commands.
A list of the most common shell signal numbers are listed in the table.

A typical program that makes use of the trap command is :
# small program to read the / usr/adm/wtmp file
# uses /etc/wtmp). It program is ineterrupted etc., the
# interrupt is trapped, and a samall message is printed.
Trap ‘echo program interrupted’ 0 1 2 3
Echo –n ‘enter a username:’
Read username
Echo
Cat /usr/ad/wtmp |grep $username
This program uses a simple trap statement to handle the shell exit, hang-up, interrupt and quit interrupt signals.
The program scans the wtmp file to look for all usernames that match the user_supplied value, stored in the shell variable supername.
Executing the program, assunming we named it finduesr, would produce a listing similar to the following:
$ finduser
Enter a username: Fred
Fred tty01 jun 13 16:45
Fred tty01 jun 16 13:45
Fred tty01 jun 17 12:45

Program interrupted
$
During the time that the program was excuted the user pressed the interrupt key.
The program dtetcted. This is done by bracketing the commands together and separating them by semicolon(;) as illustrated below:
Trap(cler; echo program terminated) 1 2
Q3) Explain for and for each construct with example.
Ans: Looping is the process of iteration within a program. When programming the shell we constantly find a need to process some information more than once.
The shell provides a number of constructs for iterative processing. The first two constructs are for (Bourne shell) and foreach(c-shell).
These constructs allow looping to take place through a series of actions. The syntax for both shell is given here:
Bourne shell C shell
For in ….. foreach …..
Do [actions….]
[actions on var>…] End
Done
The value for is an arbitrary variable name. The value for ….. are normally names of individual files.
The in part of the Bourne shell versions is optional, thus a loop can performed over each file, allowing process to take place on each pass of the loop.
The program below uses the for…done construct to loop over every file in the current directory giving the user the chance to delete the file if required.
A case statement is used to allow the yes/no confirmation to delete the current file.. The name of each file is shown on each pass of the loop.
Note that the variable file has a preceding $ because it is variable and to be revered to it must have this dollar sign.
The value for $file will be replaced on each pass of the loop by the next file in the current working directory.
When the file list is exhausted the loop will terminate.
#program 3: loop through each file in current directory
# allowing user to deklete the file I frequired.
For file *
Do
Echo –n “[“ $file”] Delete this file (y/n) ?:
Read yeno
Case $yesno in
Y|Y) Echo “ I have deletd the file[“ 4file”].”
Echo
Rm $file
;;
*) echo “keeping [“$file”].”
Echo
;;
Esac
Done
Echo “all files processed”
Notice how the program will not delete a file when a reply is not recognized.
Also note the use of the pattern (y/Y) which matches both upper and lower case letters.
Q4) Give the rules for creating shell variables in UNIX operating system.
Ans: there are various techniques that allow the user to create and manipulate shell variables.
All of the standard shell variables can be manipulated including any user defined variables that the user may wish to create.
User defined variables: creating a variable a simple exercise achieved by assigning a value to a variable identifier.
We have met several variable identifiers already, such as PS1, PS2 and PATH etc.
To create a user defined variable i.e. a variable name that is not the same as many standard shell variables, we use a command of the form:
=
Example:
$ dir=/usr/joh/sales
This commands creates a variable called dir which is assigned the value /usr/john/sales a pathname in this instance.
This variable can now be incorporated into a command such as cd which uses a pathanem as an argument:
$ cd $dir
This command changes directory to make the value of the variables dir i.e. the directory /usr/john/sales , the current working directory.
Note the $ sign on front of the variable. This is essential when refrring to any shell variable in unix.
Incorporating variable into text:
Shell variables can be incorporated into any text displayed using the echo command.
This is done by explicitly placing the shell variable within the text be displayed.
Ex: $ echo $PS1
$
$ echo ‘The value of PS1 is $PS1’
The value of PS1 is $PS1
This example demonstrates the result when we use signal quotes to enclose a text string with the echo command.
In this example echo has printed the string literally. There is no interpretation of any metacharacters within the string itself.
Q5) Explain the shell variable in UNIX.
Ans: A shell variable is an identifying characters string that can contains a range of alphanumeric data.
Variables are used extensively in the shell, and they allow the user to substitute arguments to shell commands.
They fall into two categories: standard shell variables,
some of which are set up by the shell when you log in and user defined variables which can be created by the user as required.
Every variable must have a name which begins with $(dollar) e. g. $name.
The standard Bourne shell variables are:
$home: A variable containing the full pathname of your home directory i. e. your login directory.
$shell :A variable containing the name of your login shell i.e the Bourne shell
$term: A variable containing your username. eg Fred
$ path: A variable containing the full pathnames of the directories that are searched for Unix commands i.e. ls, who etc.
Directory path names are separated by colons.
$? A variable that contains the exit status of a command
$# a variable that holds the number of arguments that a shell utility was invoked with.
User defined variables: Refer Q5d of summer 2006
Q5b) explain the case and switch constructs with syntax.
Ans: The case (bourne shell) and switch(C-shell) constructs offer alternative structures for testing.
The syntax descriptions for these two structures are shown in below:
 Bourne shell:
Case< $variable> in
Value1)
	[Actions…..]
;;
Value2)
	[actions…..]
;;
Valuye1/2)
	[actions…….]
;;
*)
[default actions……..]
;;
Esac.
C-shell
Switch(<$variable>)
Case value1:
	[action…..]
Breaksw
Case value2
	[action….]
Case value 3;
Case value 4;
	[actions…]
Breaksw
Default:
	[default actions….]
Brekasw
Endsw
The main differences between the two lie in the use of colons(* following a condition value in the C-shell version, and the use of the right bracket in the Bourne shell version.
The c-shell version of the construct allows multiple value to be represented by simply repeating a case statement, whereas Bourne shell versions uses the pipe character (|) to separate possible values.
Double(;;) are used to end a series of stamen in the Bourne shell versions, whereas the word breaksw is used in the C-shell version of the construct.
A default value is represented by an asterisk(*) in a Bourne shell construct, where as the C-sahell version uses the word default and the main difference is of the name themselves such that case….esae and switch………endsw
The example below illustrates the use of the Bourne shell versions of the construct in a simple program.
That checks the current value of the $TERM variable to see if it contains a vt100 emulation.
If the terminal is set up with this emulation then the vi editor is invoked to edit a file, the name of the which is supplied by the user.
If the vt100 value is not found in the $TERM variable, it is set by the program and vi is invoked.
#program 2: uses case… esac to obtain a file name.
# set terminal type and edit file. Assume
# the user file exists in current directory.
Echo –n “eneter the file you want to edit:”
Read file
# see if user’s file actually exists
If[-r $file]
Then
Case $term in vt100|vt)
Echo “terminal recognized as vt100….”
Echo
Vi $file
;;
*)
Echo “terminal not recognized ,setting to vt100….”
Echo
Term =vt100
Vi $FILE
;;
Esac
Else
Echo “I cannot find that file”

Notice that how the case....esac construct in this program is embedded within an if…fi construct.

Q6) What is the purpose of “Awk” in shell script? Explain with example.
Ans: Awk is pattern scnning and processing languge which works in much the same way as sed, although using awk is similar to programming in the shell.
The most useful awk programs should be placed in files for convenience an dthen executed.
When used from the interactive level, the syntax description of awk is as foolows:
Awk ‘
Used in a program awk take sthe following from:
Awk{action}
When awk is executed it reads its input from the input files file1….filen one line at a time.
The lines in these files are compared with each in turn.
If the pattern matches the line, then the corresponding {actions} is performed.
Any output produced by awk does not go to a file unless output redirection is employed by the user.
The input files used by the awk are also left untouched during processing, so remain unaltered.
Examples:
$ awk ‘/wombat/’{print} file1 file2
This command searches the files named file 1, file2 for the pattern wombat.
If the pattern is matched in either of the files, the line containing that pattern is displayed.
The different “awk” utilities:
Field processing with awk: when awk runs it divides each input into a series of fields which must normally be separated by at least one or more spaces ao that they can be distinguished from each other. Take the who listing.
The listing supplied by who can be thought of as five field columns:
$ who
Doug tty08 jun 16 12:09
Pam tty10 jun 13 12:34
If we were using a awk and wanted to refer to these fields, we would use a notation similar to that of the positional parameter.
The notation awk used is s1…….$NF
Note that the absence of a $0 field. $0 still exists in awk, although it is not used to refer to individual fields.
The variable $NF is maintained automatically by awk and is equal to the total number of fields.
In this case of the who listing the value of $NF would be 5. Now that how to refer to individual fields from command listings.
We can manipulate any shell command whose output is divided into separate columns. For example:
$ who |awk ‘{print $1}’
Doug
Pauline
$
Thus uses awk as a filter whose input is arriving from the who command.
As the data arrives awk divides it up into fields and carries out the commands(s) within the braces({}),print $1.
BEGIN {} and END {} constructs:
Awk provides the constructs BEGIN and END which allows the action to be perofmrd before the first line of the input has been processed and after the last line of input ahs been processed.
Tak the short awk excerpts which follows: Awk –F:’
BEGIN {print all users in /etc/passwd file
Print
}
{print $1}
END{ print
Rpint End of file}’/etc/passwd
This code uses the begin statement to print the simple heading and then a blank line followed by a list of each username in the /etc/passwd file.
The END stamen ensures that a short message is printed when processing finishes.
Note that how single quotes are placed strategically right at the start and t the end of the file.
The file to be processed appears outside the quotes at the end of the program.
When BEGIN and END are used the awk instructions to be carried out must be used without the other if necessary.
Regular expression: Awk also handles regular expressions. A search string must be delimited by/slashes as follows:
/string/
The Tilde(~) is used to match a regular expression and the opearator !~ inverse the matching process.
These are used in the examples below. Example:
$ awk ‘$1!` !~ /joh/’ address_book
Mark smith 12 circle Garden Wimbledon swl9
This command will make awk search for all entries where the first filed ($1) does not match the pattern john.

Q7) Explain the commands while and until used in UNIX shell scripts.
Ans: The while and until constructs provide another looping mechanism slightly different to the for and for each constructs .The syntax for these constructs are given as follows:
Bourne Shell
While[]
Do
[actions….]
Done
C-shell
While()
	[actions…]
End
While loops are useful since they execute until some condition is set true. The exit status of a command can thus be used to control the iterations of a loop. For loops iterate for a more specific duration. Such as over a list of files etc. whereas the iteration duration of a while loop is definite. Since the outcome of a shell command may be less certain. Both the whiles loop and until loop depends on the exit status of a command in order to control the loop –body. This can be thought of as the instructions between the do and done or the while and end statements. Take the following example:
While[1]
Do
Who | grep john
Sleep 300
Done
This small program uses a single value as the command list. The existence of a value recognized as true condition, thus the loop will execute infinitely. He body of the loop contains the command who \grep john which runs the who command to check if the user named john is currently logged in. Until construct: The until construct available only under the bourne shell. Take the following example below where the same program is implemented using an until construct:
Until who | grep tty01
Do
Echo ‘ No user on tty01 yet.’
Sleep 120
Done
In this program the main body of the loop is repeated until the command who|grep tty01 command returns failure. Thus an entry is only printed once, where the user using tty01 is found upon execution of the program. The program will iterate in the case where somebody is not using the terminal tty01.

Q8) Explain with any two options of test command.
Ans:The test command can be used directly from the shell prompt, although it is mainly used in shell scripts in test conditions for if statements. The test command can be used according to the two following syntax descriptions: i) Test Or ii) Ii) [] Note that the second syntax in the square brackets do nit denotes an optional clause. The clause to which we are referring can be made up of two things, namely i) string patterns and ii) filenames The test command alters the $?. The Bourne Shell status variables after performing a test. If the value of an expression is true the test command returns a zero (0) exit status, otherwise it returns a nonzero status. The actual condition we test determined according by the following option.


For accessing computer programs go to TECHNOLOGY