Learning Objectives:
1.
2.
3.
To learn the usage of environment (shell) variables in shell programming To understand the handling of command line arguments To illustrate more useful commands in shell programming using examples
Keyword Example
$ cat env #!/bin/sh echo "Hi $USER!" echo "Your home is: $HOME" echo "Your path is: $PATH" echo "Your current directory is: $PWD" echo "Your shell is: $SHELL" echo "Your printer is: $PRINTER" $ env Hi horner! Your home is: /homes/horner Your path is:/usr/bin:.:.:/homes/horner/Unix/bin:... Your current directory is: /homes/horner/111 Your shell is: /bin/csh Your printer is: csl3
With more than 9 arguments, they are still stored, but they have to be moved using the shift command before they can be accessed.
$ shiftargs arg1 The args are 0 = The args are 0 = The args are 0 =
arg2 arg3 shiftarg, 1 = arg1, 2 = arg2 shiftarg, 1 = arg2, 2 = arg3 shiftarg, 1 = arg3, 2 =
f1 f2 f3 ... fn_1 fn
The set command is useful for moving the output of command substitution into the args:
$ date Thu Feb 25 17:06:27 HKT 1999 $ cat day #!/bin/sh set `date` echo "Today is $3 $2 $6" $ day Today is 25 Feb 1999
./secret/letter1 ./secret/letter2
$ treeproc usage: treeproc <pattern> [<command>] $ treeproc "*1" Running "echo" for *1 in dir: /home/kwchiu ./secret/letter1 $ treeproc "letter*" rm -i Running "rm -i" for letter* in dir: /home/kwchiu rm: remove ./letter0 (yes/no)? rm: remove ./secrete/letter1 (yes/no)? rm: remove ./secrete/letter2 (yes/no)? $ find . -name "letter*" -exec rm -i {} \; (same as the above) {} substitutes each filename
Return Status $?
In UNIX, after a command (or your own program) finishes execution, it returns an exit code to its parent. The shell can retrieve this code with $?.
$ ls /dev/null is a special device dumps everything input to it name $ cat testif if cat $1 >/dev/null 2>&1 The construct >file 2>&1 is useful then for logging. Both the stdout and echo "OK" stderr are sent to the same file. else echo "Problem: Code" $? fi $ testif name OK $? returns the previous $ testif abc exit code Problem: Code 2