Unix Shell Programming
Command Separation & Grouping
Characters that separate commands
- '\n' (newline) initiates execution of the command preceding it.
Note: if you type '\' before pressing the <ENTER> key, the newline
is quoted, and treated like a space
- ';' separates commands on a single line
- '|' combines separate commands into a single command called a pipeline
- '&' runs the preceding command in the background
Operator precedence
- '|' has highest precedence
- '&' is next
- ';' has lowest precedence
- groupings made explicitly with parentheses
Command Separation & Grouping
Examples
- date ; who
- date ; who | wc
(date ; who) | wc
(date ; who) | tee save | wc
- (sleep 5 ; date) & date
- echo At the tone the time will be 'date'
Variables
Variables contain values, set explicitly or by the system
- varname=value sets the variable value
- $varname or ${varname} represents the value of the variable
- you can view a variable's value with echo
- variables may be exported to all subshells with export
Examples
- echo $SHELL
- TERM=vt100 ; export TERM
- PATH = "$HOME/mybin:$PATH"
- VISUAL=$(whence emacs)
- PS1='! $PWD> '
Read-Only Shell Variables
Some variables may only be read by shell scripts
- Command line arguments
- PID numbers
- Exit status
Control-Flow Commands
Conditionals
Conditionals test the value of a condition, i.e. the exit status of
a command
- if command executed successfully, exit status = 0 (TRUE)
- boolean expressions in [[ ]] construct may also be evaluated
- if several commands follow "if", final exit status used
- boolean operators may combine results
String comparisions
- str = pat # two strings match
- str != pat # two strings do not match
- str < pat # str precedes pat in alphabetical ordering
- str > pat # str follows pat in alphabetical ordering
- -n str # str is not null (length > 0)
- -z str # str is null (length = 0)
File checking
- -a file # file exists
- -d file # file is a directory
- -f file # file is an ordinary file
- -r file # user has read permissions on file
- -s file # file is not empty
- -w file # user has write permissions on file
- -x file # user has execute/search permissions on file
- -O file # user owns the file
- -G file # user has same group ID as file
- file1-nt file2 # file1 is newer than file2
- file1 -ot file2 # file1 is older than file2
Integer comparisions
- -lt # less than
- -le # less than or equal to
- -eq # equal to
- -ge # greater than or equal to
- -gt # greater than
- -ne # not equal to
if then
Syntax:
Example:
if then else
Syntax:
Example:
if then elif
Syntax:
Example:
if [[ $1 < $2 ]] ; then
print "$1 < $2"
elif [[ $1 > $2 ]] ; then
print "$1 > $2"
else
print "$1 = $2"
fi
for in
Syntax:
Example:
for
Syntax:
Example: