Shell Programming: Branches
Shell Programming: Branches
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
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 ]
-lt less than -le less than or equal -gt greater than -ge greater than or equal -eq equal to -ne not equal to
$ X=abc
$[ $X = abc ] $ echo $? 0
$ X=abc
$ [ $X != abc ] $ echo $? 1
$ echo $?
1
test
option filename
Example:
$ test f funfile $ echo $?
0
$ test d funfile
echo $? 1
-r
-x
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
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 ;;
exit 99
$ exit_test