Bourne Shell Programming – Topics Covered Shell variables Using options using getopts Using Quotes Reading Data Arithmetic On Shell Environment and subshells Passing Arguments Parameter substitution Testing conditions Using set Branching I/O redirection if-else, if-elif, case Shell archives Looping The eval, trap, wait commands while, for, until break and continue 1
Part 1 Some Regular Expression Characters . (dot) – any character ^ - beginning of line $ - end of line * - zero or more occurences of previous regular expression [chars] – any character in the set of chars [^chars] – any character not in chars . \{min,max\} – at least min occurences and at most max occurences of the previous regular expression. 2
Shell Scripts Bourne Shell/Korn Shell Invoking a shell script $shell_script_file or $sh -options shell_script_file the script file must have execute-permission. Shell Variables mydir=/usr/jsmith/bin count= #assign a null value to the variable echo $mydir #display the contents of mvdir x=* echo $x #substitutes the names of the files in the directory #name of a command, options and arguments can be stored inside variables command=ls option=-l filename=namesFile $command $option $filename #shell performs the variable substitution before it # executes the command. 3 2
Quotes The Double Quote The Single Quote The special characters, $ , back The white-space characters quotes ( ` ) and back slashes ( \ ) are enclosed between the single not ignored. quotes are preserved by the Example; shell. x=* The special characters are echo $x # filenames are substituted ignored. Example: echo ‘$x’ #$x is displayed filename=/usr/jsmith/bin/prog1 echo $filename echo “$x” # * is displayed, variable echo ‘$filename’ substitution is done inside the double quotes, echo ‘<> | ; () {} ` & “‘ no file name substitution is done and * is passed to the shell. 4
Quotes The Back Slash The Back Quote Is same as putting single quotes purpose is to tell the shell to around a single character. execute the enclosed command Quotes the single character that and to insert the standard output immediately follows it. from the command at that point X=* on the command line. echo \$x # $x is displayed Example: Is interpreted inside the double echo The date and time is: `date` quotes. echo There are `who | wc -l` users Use backslash inside the double logged on quotes to remove the meaning of filelist=`ls` characters that otherwise would be interpreted. echo $filelist (#what is the output) Examples: mail `sort -u names` < memo echo “ \ $x” #$x is displayed #-u option removes the duplicate echo “The value of x is \ ”$x \ ”” # entries from the file #The value of x is “5” is displayed 5
Arithmetic On Shell A variable is just considered a string of characters. Example: x=1 x=$x+1 echo $x #will display 1+1 A unix program expr evaluates an expression given to it on the command line. Each operator and operand given to expr must be a separate argument. The operators, +, -, *, /, % are recognized. Example: i=1 i=`expr $i + 1` Evaluates only integer arithmetic expressions. awk may be used for floating point calculations. expr 10 * 2 # what is the problem with this? 6
Passing Arguments $#: Number of arguments passed to the program from the command line. $* : references all the arguments Example: %cat showArgs echo $# arguments passed. echo they are :$*: %showArgs a b c d 1 #output - %showArgs “a b c d 1” #output - % showArgs `cat names` #output - % showArgs x* #output - %cat lookup grep $1 phonebook lookup “Mary Jones” What is the result? 7
Positional Parameters Positional parameters set shell script arguments. e.g. $my_script a b xy “1 2 3” positional parameters have the values $0 -- my_script $1 -- a $2 -- b $3 -- xy $4 -- 1 2 3 $* - references all the variables passed as arguments 8
The shift command shift %cat testshift echo $# $* left-shifts the positional parameters. shift If more than 9 arguments echo $# $* are supplied, arguments 10 shift and up cannot be echo $# $* referenced. use shift to access these % cat testshift 1 2 3 4 5 6 7 8 9 10 arguments. What is the output? shift assigns value in $2 into $1, $3 into $2 etc. The number of arguments ($#) gets decremented by one on each shift. 9
Testing Conditions if statement: allows to test a condition and branch on the exit status of the condition tested. An exit status of 0 indicates the program executed successfully. An exit status of non-zero indicates a failure. $?: contains the exit status of the last command executed. Operators for integer comparisons eq (equal), -ge (greater than or equal), -gt (greater than), le (less than or equal), -lt (less than) and – ne (not equal) Operators for string comparisons = , !=, -n (string is not null) and – z (string is null) File operators -d file file is a directory -f file file is an ordinary file -r file file is readable by the process -s file is of non-zero length 10
Testing Conditions Examples user=$1 who | grep “^$user” > /dev/null - the exit status of the last command in the pipe line is returned. 11
The test command The test command is used to test one or more conditions in an if statement. y=ABC test "$y" = ABC echo $? # displays 0 x= test -n x #checks if x is not null echo $? #displays 1 test -z x #checks if string is null echo $? x=ABC [ "$x" = ABC ] #[] same as using test [ ! "$x" = ABC ] x=5 # -a for logical and -o for logical or [ "$x" -ge 0 -a "$x" -lt 10 ] [ - f “$file1” -a - r “$file1” ] 12
Branching %cat isUserOn #checks if a user is logged on User=$1 if who | grep “$user” # what is the problem with matching a username in the output of who? then echo “$user is logged on” fi ======================================== if [ “$#” -ne 1 ] #checking for the correct number of arguments then echo “Incorrect number of args” exit 1 #terminates the program with the exit status fi if [“$NAME” = “John Doe” - a “$BAL” -gt 5000] then echo “ok” else 13 echo “not ok” fi
Using case case: allows a comparison of a single character against other values and execute a command if a match is found. %cat ctype x=A case "$x“ # The value in x is compared with each of the cases #until a match is found. When a match is found, the #commands up to the double colons are executed . in [0-9] ) echo digit;; [A-Z] ) echo uppercase;; [a-z ) echo lowercase;; * ) echo special character;; esac Exercise: Can you rewrite the script passing the value to be tested as an argument? 14
The && and || constructs command1 && command2 if the exit status of command 1 is 0 then command 2 is executed. Example EDITOR=[ -z "$EDITOR" ] && EDITOR=/bin/ed echo "$EDITOR" command1 || command2 If the exit status of command 1 is not zero, then command 2 is executed. Example: grep “$name” phonebook || echo “Couldn’t find name” 15
Debugging with a -x option sh -x ctype A Trace the execution of any + [ 1 -eq 1 ] program by typing in sh -x followed by the name of the + x=A program and its arguments. + + echo A Starts up a new shell to execute + wc -c the program with the debug num=2 option. + [ 2 -ne 1 ] Commands are printed at the + echo Enter a single character terminal as they are executed Enter a single character preceded by a + sign. + exit 1
Looping The for loop is executed for as many words as are included after in for var in listofwords do commands done for i in 1 2 3 do echo $i done for file in * #substitutes all the files in the # directory do processCmd $file done
The for loop for var #uses all the arguments given to the program on the command line do command command done for file in $* # Replaces $1, $2 as $1, $2 etc do x=`wc -l $file` echo There are `echo $x |cut -f1 - d’ ‘` lines in $file done for file in “$@” #Replaces $1, $2 as “$1”, “$2” etc. Should be included in double quotes do echo $file done 18
Looping while command until command do do command1 command1 command2 command2 done done command1 and 2 are executed until command1 and command2 are command returns a nonzero exit executed as long as command status returns a non-zero exit status. until who | grep “^$user “ # Print command line arguments while [ “$#” -ne 0 ] do do sleep 60 echo “$1” done shift done
Break and continue break: to break out of a loop. continue : the remaining commands break n: to break out of n inner most loops in the loop are skipped. for file for file do do #variable error can be set to a value if [ ! - f “$file” ] count=1 while [ “$count” -le 5 ] then do echo “$file not found” #process file continue if [ - n “$error” ] #contains a value fi then break 2 cat $file fi done count=`expr $count + 1` done done
Recommend
More recommend