Shell Programming
Branches
Return Codes
The shell variable ? holds the return code of the last command executed:
0: Non-zero: Examples: $ true $ echo $? 0 $ ls $ echo $? 0 $ false $ echo $? 1 $ cp $ echo $? 1 command completed without error command terminated in error
The test command
Syntax:
test expression
or
[ expression ]
The test command can evaluate the condition of Integers
Strings
Files
Cont.
The test command writes nothing to standard output. You must display the value of the return code to determine the result of the test command There must be white space around [ and ]
The test command (numeric)
Syntax:
[ number relation number ]
Relations:
-lt less than -le less than or equal -gt greater than -ge greater than or equal -eq equal to -ne not equal to
Example: Assume X=3
$ [ $X lt 7 ] $ echo $? $ [ $X gt 7 ] $ echo $?
*variable must have a value
*you should surround all $variable expressions with double quotation marks to avoid improper variable substitution by the shell
The test command-string tests
Syntax:
[ string1 = string2 ]
[ string1 != string2 ] Example:
$ X=abc
$[ $X = abc ] $ echo $? 0
$ X=abc
$ [ $X != abc ] $ echo $? 1
Numerical versus String comparison
$ X=03 $ Y=3 $[ $X $ echo $? 0 $[ $X = $Y ] -eq $Y ]
$ echo $?
1
The test command-file tests
Syntax:
test
option filename
Example:
$ test f funfile $ echo $?
0
$ test d funfile
echo $? 1
-r
to test if file is readable
-w to test if file is write-able
-x
to test if file is executable
The test command-other operators
Syntax: -o -a ! or and Not \( \) Grouping
Examples:
$[ $ANS $[ $NUM
y o $ANS
Y ] 20 ]
-gt 10 a
$NUM lt file
$ test s file a r
The if construct
Syntax:
if
test s funfile then echo funfile exists fi echo hello
The if-else construct
Syntax:
if [ $X lt 10 ] then echo X is less than 10 else
echo X is not less than 10
fi
The case construct
case $ANS in
yes)
no)
echo O.K.
;; echo no go ;; echo no option ;;
*)
esac
$ gedit menu_with_case
echo echo echo echo echo read choice case $choice in [dD]*) [wW]*) date ;; who ;; command menu d to display time and date w to display logged in users l to list contents of current directory0 please enter your choice
l*|L*)
*) esac
ls ;;
echo Invalid Selection ;;
The exit command
Syntax: exit [arg] Example: $ gedit exit_test echo exiting program now
exit 99
$ exit_test