CPIT 260 Operating Systems Lab

SHELL Programming

Lab objectives 
Understanding what is a SHELL script  First simple SHELL script  SHELL variables  User defined variables  System variables  Assigning values to variables  Reading input  Arithmetic in SHELL script  Control Structures  Decision control  Repetition control

Understanding what is a SHELL script 
Shell A shell is a command line interpreter. It takes commands and executes them. As such, it implements a programming language.  Shell scripts A shell script or a shell program is a series of commands put in a file and executed by the Shell  Why Shell scripts? Since the user cannot interact with the kernel directly, Shell programming skills are a must to be able to exploit the power of LINUX to the fullest extent. A shell script can be used for variety of tasks and some of them are listed below.

Benefit of Shell scripts 
Shell scripts allow the reusability of code  Customizing your work environment For Example Every time you login, if you want to see the current date, a welcome message, and the list of users who have logged in you can write a shell script for the same.  Automating repetitive tasks. For example, to back up all the programs at the end of the day, shutting down the system, formatting a disk, creating a file system etc.  Performing some operations on many files.

First simple SHELL script 
Create a file named SS1 (shell script 1) and type the following as content.  Example1 :  Use the command: kwrite ss1 # SS1 ls who Pwd  Save the file, the file is executed as follows:

First simple SHELL script  ---> SS1 SS1: Command not Found.  Now you do not have the permission to execute the file./ss1 .  ---> . chmod u+x ss1 ./SS1 SS1: Permission Denied. That is because the default permission given for any file is with out execute permission. How to know the default permission? change the permission and execute the file again. The reason for this message is that the path of this command should be specified because the current directory is not in the PATH environment variable.

etc. .SHELL variables  The variables in the Shell are classified as:  User defined variables : defined by the user for his use (e.  Predefined variables : reserved variables used by the shell and Linux commands for specifying the exit status of command. LOGNAME. arguments to the shell scripts.  Environmental variables : defined by shell for its own operations (PATH. HOME. SHELL etc).g age=32).

When a command complete successfully.  ? is a variable which is set internally by the shell. it returns 0 otherwise it returns nonzero. it means that the previous command was successful and if output is nonzero. . Which can be displayed using the echo command. it shows the status of the last command executed. it means that the previous command failed.  echo $? If output of this is 0 (Zero).The (?) variable  How to know exit status of any command All commands return the exit status to a pre-defined Shell Variable µ?¶ .

SHELL variables  Example: name=Amal #variable name is assigned a value Amal echo $name #Amal will be displayed echo Hello $name! . Welcome to $HOME Note: don¶t leave space between the variable and the equal (=) and the string value .

For example:  Example: # SS2 # An interactive shell script echo What is your name? read name echo Hello $name. . assigns this to the variable name and then displays the value of this variable to standard output.  This prompts the user for input.SHELL variables  To read input into a shell script use the read command.

For example:  Example : # SS3 echo "Please enter your first name" echo "followed by your family name" read name1 name2 echo "Welcome to KAU .$name2³ Note: the use of ³ ´ is optional .SHELL variables  If there is more than one word in the input. $name1 --. each word can be assigned to a different variable. Any words left over are assigned to the last named variable.

SHELL variables  Example4: # SS4 # This script takes two file names and copies the first file into the second one echo ³Please Enter source file name´ read source echo ³Enter the target file name´ read target cp $source $target echo file $source is copied into the $target .

ls | grep b Bash will run both commands. The ls program produces a list of files in the current directory.Piping  Pipes allow separate processes to communicate with each other such that the output of the first command become the input of the second command.  Example: suppose that the current directory is your home. while the grep program reads the output of ls and prints only those words containing the letter b. . connecting the output of the first to the input of the second.

it counts the number of lines (i. If we use the option ±c. words or characterss. it will count the characters number. If we use the option ±w. current users). it will count the words number.e. Command Substitution : Format for command substitution is : var=`command` (where ` ` is back quote)  Examples: echo the current date is `date` # It will display the output of date command echo there are `who | wc ±l` users working on the system # see output of this Note: wc will count number of lines. While we use the option ±l. .

 Example: echo there are `cat lab | wc ±w` words in the file lab This command will print a message that shows the number of the words in the file lab .

Arithmetic in SHELL script  Various forms for performing computations on shell variables using expr command are :  expr val_1 op val_2 (Where op is operator)  expr $var_1 op $var_2  var_3=`expr $var_1 op $varl_2` (var_3 is written without $) .

Arithmetic in SHELL script  Examples : expr 5 + 7 # Gives 12 expr 6 ± 3 # Gives 3 expr 3 \* 4 # Gives 12 (removing \ will produce syntax error) expr 24 / 3 # Gives 8 expr 24 % 3 # Gives 0  Note: you must leave space before and after the operators sum=`expr 5 + 6` echo $sum # Gives 11 a=12 b=90 echo sum is $a + $b # Will display: sum is 12 + 90 echo sum is `expr $a + $b` # Will display: sum is 102 .

 This is examined by the exit status of each command. . if and only if the preceding command failed.  The || operator executes the command following it.e whether the previous command has succeeded or failed.Conditional Execution Operators && (command1 && command2) || double pipe (command1 || command2)  Conditional execution of commands are useful when we want to execute the command based on the status of the previous command.  The operator && executes the command following it. if and only if the preceding command was successfully executed. i . For success of any command exit status will be 0 (zero) and 1 (or non zero) if unsuccessful.

In such cases the if-then-elif-else-fi statement is used. then this type of conditional execution is not helpful. . and if it failed to find µsara¶ it will display the message: µThe name is not found¶ In case that more than one command must be executed or more than one condition need to be checked simultaneously . and print an interactive message otherwise . then use the command: rm try && echo file is removed successfully The above command will remove try if it exits.  Suppose that you are in hw1 and it includes the file lab: grep µsara¶ lab || echo The name is not found The above command searches for µsara¶ in lab.Conditional Execution Operators Examples of using && and || :  Create a file in your home and name it try. it will do nothing.

 The test command does not produce any output. . i.test command  The Linux system provides test command which investigates some conditions and translate the result in the form of success or failure.e either a 0 or 1. but its exit status can be passed to the if statement to check whether the test failed or succeeded .

test Command The test command has specific operators to operate on files. numeric values and strings which are explained as following: .

test Command  Operators on Numeric Variables used with test command -eq : equal to -ne : not equals to -gt : grater than -lt : less than -ge : greater than or equal to -le : less than or equal to .

(Indicates that exit status is false) .test Command  Examples: a=12. b=23 test $a ±eq $b echo $? This code gives 1 (one) as an output.

test Command  Operators on String Variables used with test command : string1 = string2 : true if string1 and 2 are the same string1 != string2 : true if string1 and 2 are different -z string : true if string length is zero -n string : true if string length is non zero .

test ±z $address # will return 0 as the variable has not been defined. or write every command in one line and follow it by pressing the Enter button .test Command  Examples : name=³Sara´ test ±z $name # will return the exit status 1 as the string name is not null test ±n $name # will return 0 as the string is not null. In case of the direct writing in the shell. test $name = ³Amal´ # will return 1 as the value of name is not equal to ³Amal´  Notes:  you must leave one space before and after every operator  The using of ³ ´ is optional  You can but the code in text file or type it in the shell. either write the commands after each other and separate them by .

 -w : file exists and has write permission (used with files and directories).  -s : the file exists and the size is non zero (used with files and directories).  -d : the file exists and is a directory (only used to find directories).  -x : file exists and has execute permission (used with files and directories). .  -r : file exits and has read permission (used with files and directories).test Command Operators on files used with test command :  -f : the file exists and is a regular file (only used to find files).

and ±x operators test the read. They can be used with files and directories .test Command Examples:  test ±f ³lab´ # Will check for the file lab . returns 0 else 1  test ±r ³lab´ # Will check for read permission for lab  test ±d ³$HOME´ # Will check for the existence of the home directory  test ±d ~/mylab/hw2 # Will check for the existence of the hw2 directory  Notes: The using of ³ ´ is optional The search for a file or a directory will not provide true unless it exists in the current working directory or it is mentioned with the complete path The ±r. write. if exists. and execute permissions of the owner. ±w.

OR and NOT operators.Logical Operators used with test command  Combining more than one condition is done through the logical AND.  -a : logical AND  -o : logical OR  ! : logical NOT .

test $name != sara .Logical Operators used with test command  Example : create new file in hw1 and name it tmp  test  test  test  test  test  test ±r ³tmp´ ±a ±w ³tmp´ # will provide true ! ±r ³tmp´ ±a ! ±w ³tmp´ # will provide false ±r ³tmp´ ±a ±x ³tmp´ # will provide false ±r ³tmp´ ±a ! ±x ³tmp´ # will provide true ±r ³tmp´ ±a ±w ³tmp´ ±a ±x ³tmp´ # will provide false ! -x ³tmp´ # will provide true # will provide false  name=sara .

[ condition ]  you can use [ condition ] exactly as test command  Examples of [ ] and test: similar to test $a ±eq $b [ $a ±eq $b ] [ ! $a ±eq $b ] similar to test ! $a ±eq $b similar to test ±z $name [ ±z $name ] [ ±n $name ] similar to test ±n $name [ $name1 == $name2 ] similar to test $name1 == $name2 [ $name1 != $name2 ] similar to test $name1 != $name2 [ -n $name ] similar to test -n $name similar to test ±r ³lab´ [ ±r ³lab´ ] [ ±r ³tmp´ ±a ±w ³tmp´ ] similar to test ±r ³tmp´ ±a ±w ³tmp´ [ $a ±gt $b -o $a ±eq 0 ] similar to test $a ±gt $b -o $a ±eq 0 .

[ condition ]  Examples of using ! [ 3 ±gt 2 ±o 3 ±gt 1 ] true [ ! 3 ±gt 2 ±o 3 ±gt 1 ] true [ ! 3 ±gt 2 ±o ! 3 ±gt 1 ] false [ µsara¶ != µamal¶ ] true [ ! µsara¶ = µamal¶ ] true .

if statement  The if statement The if statement uses the exit status of the given command and conditionally executes the statements following. Make sure that you end each if statement with an fi statement. (semicolon). then. The general syntax is: if test then commands (if condition is true) else commands (if condition is false) fi  if. else and fi are shell reserved words and are only recognized after a new line or . .

else if test then . fi .... For example: if test then .. elif test then ....if statement  Nested if statement : if test then . fi fi The elif statement can be used as shorthand for an else if statement..

if statement example  Example : x=3 if test $x -eq 2 then echo it is two else if test $x -eq 3 then echo it is three fi fi  The example can be written as following: x=3 if [ $x -eq 2 ] then echo it is two elif [ $x -eq 3 ] then echo it is three fi .

if statement example #SS10 #To show use of if statement # Read three unequal numbers and display #the largest clear echo -n "Enter the first number :" read num1 echo -n "Enter the second number :" read num2 echo -n "Enter the third number :" read num3 #note: using -n with echo force the curser # to remain in the same line if test $num1 -gt $num2 then if test $num1 -gt $num3 then echo $num1 is the largest else echo $num3 is the largest fi else if test $num2 -gt $num3 then echo $num2 is largest else echo $num3 is the largest fi fi .

 Program flow is controlled on the basis of the word given.Flow of control statements  The case statement : The case statement is a flow control construct that provides for multi-way branching based on patterns. This word is compared with each pattern in order until a match is found. . then the associated command(s) are executed.

 The * character can be used to specify a default pattern as the * character is the shell wildcard character. command2 « ... command2 « . pattern2) command1. command2 « .).Flow of control statements case word in pattern1) command1. Each list of commands must end with a double semicolon (.. --------------------------------------------patternN) command1. . esac  Notes:  When all the commands are executed control is passed to the first statement after the esac. otherwise a syntax error will be produced.. command2 « .  If there is more than one pattern have the same commands .. *) default command1. default command2 « . separate the patterns by | as follows: pattern1 | pattern11) command1..  The pattern and word can be number or letter or string.

esac . *) echo wrong choice.case statement example #SS11 echo ²n Enter a letter between a and d: read choice case $choice in A | a) date.. B | b) ls -l. C | c) who ... D | d) pwd ... echo $HOME.

case statement example #SS12 # Display a menu of options and # depending upon the user's choice. Date and home" echo echo ³b. C | c) who . c or d ): read choice case $choice in A | a) date. D | d) pwd .... echo $HOME. b. Current Directory" echo echo ±n Enter choice (a. *) echo wrong choice. Directory listing" echo echo ³c. #execute associated command #Display the options to the users clear echo ³a. Users information " echo echo ³d... B | b) ls -l. esac .

done . Small loops can be written on a single line as following: for var in list .For statement  The for loop notation has the general syntax: for var in list-of-words do commands done  Notes:  commands is a sequence of one or more commands separated by a newline or .  The reserved words for. and done must be preceded by a newline or .  The members of list-of-words must be separated by spaces only.Loops . (semicolon). (semicolon). do. do commands.

create a shell script and name it ssfor. In the shell script write the following code: for i in 1 2 3 do echo iteration $i done .For statement example  cd to your home.

In the shell script write the following code: for i in `ls $HOME` do if test -f $i then echo the $i is a file ilef test -d $i then echo the $i is a directory else echo the $i is neither file nor directory fi done .For statement example  cd to your home. create a shell script and name it ssfor1.

i<=3 . i++ )) do echo Hello done .For statement with another syntax  The following example show another syntax to For statement: for (( i=0 .

and if the exit status of the last command in them is 0 (zero).)  The commands in test commands are executed.e true). . the commands in command-list are executed.The while statement  The while statement has the general syntax: while test commands do command-list done  Notes:  If test commands includes more that one command they must be separated by semicolon (.  The sequence is repeated as long as the exit status of test commands is 0 (i.

1` done .The while statement example  Create a shell script and name it sswhile. Write inside it the following code: count=5 while test $count -ge 0 do echo the counter has the value: $count count=`expr $count .

1` limit=`expr $limit + 1` done .The while statement example  Create a shell script and name it sswhile1. Write inside it the following code: count=5 limit=0 while test $count -ge 0 -a $limit -lt 3 do echo the counter has the value: $count echo the limit has the value: $limit echo -----------count=`expr $count .

false).The until statement  The until statement has the general syntax: until test commands do command-list done  Notes:  This is identical in function to the while command except that the loop is executed as long as the exit status of test commands is nonzero (i. .e.

.The until statement example  Create a shell script and name it ssuntil. Write inside it the following code: # Accept the login name from the user clear echo Please Enter the user login name: read name until who | grep -i $name do echo Please Enter the user login name: read name done echo The login name is true  This example will repeat the loop until a true login name is entered.

 To exit from n levels.  The continue command causes execution to resume at the while.  The break command terminates the execution of the innermost enclosing loop. causing execution to resume after the nearest done statement.The break and continue statements  It is often necessary to handle exception conditions within loops and the statements break and continue are used for this purpose. until or for statement which begins the loop containing the continue command. (semicolon). .  The reserved words break and continue must be preceded by a newline or . use the command: break n  This will cause execution to resume after the done n levels up.

esac done # do the command  This prompts the user to enter a command. echo ³after break´ . echo ³after continue´. To stop the command the user enters out at the prompt. .. Write inside it the following code: while echo Please enter command do read response case $response in out) echo ³we will break´.. # no more commands "") echo ³we will continue´. # null command *) $response . While he enter a command or null string the script continues to run. continue.Example of using the break and continue statements  Create a shell script and name it ssbreak.. break.

Example of using the break n Create two shell script and write inside them the following code: #ssbreak2 for i in 1 2 3 do echo this is $i in outer loop for j in a b c do echo this is $j in inner loop break done done #ssbreak3 for i in 1 2 3 do echo this is $i in outer loop for j in a b c do echo this is $j in inner loop break 2 done done .

and observe the output for each program.Lab work  Run all the programs given in the Lab Notes. .

Sign up to vote on this title
UsefulNot useful