KORN SHELL PROGRAMMING CHEAT SHEET
Special Characters
Metacharacters have special meaning to the shell unless quoted (by preceding it with a \ or enclosing it in ` `)
Inside double quotes “ “ parameter and command substitution occur and \ quotes characters \`”$
Inside grave quotes ` ` then \ quotes characters \'$ and also “ if grave quotes are within double quotes
Input / Output
Input and output of a command can be redirected:
<file Use file as standard input (file descriptor 0)
>file Use file as standard output (file descriptor 1)
>|file As above, but overrides the noclobber option
>>file Use file as standard output, appending if it already exists
<>file open file for reading and writing as standard input
<<word Here document. The shell script is read as standard input until word is encountered.
Unless a character of word is quoted, parameter and command substitution occur. Newline is ignored.
\ must be used to quote \ $ `
<<-word As above, but leading tabs are stripped
<&digit Standard input is duplicated from the file descriptor digit
>&digit Standard output is duplicated from the file descriptor digit
Eg. >&2 will redirect standard output to standard error
<&- Close standard input
>&- Close standard output
Commands
; sequential execution, return status is that of the last in the list
& background execution
(cd /tmp; ls; ls | wc -l) & sequential background execution
&& AND – execute both, return true of both succeed
|| OR execute the first, if false, execute the second, return true if either succeed
$(command) stdout of command substituted eg. DATE=`date +”%Y-%m-%d”`
`command` alternate form of above, but has problems handling quotes and backquotes
Functions
A name used as a simple command to call a compound command with new positional parameters.
fname() {command list}
Expansions occur during each execution of the function, not during the function definition.
Exit status of a function call is the exit status of the last command executed within the function.
Signals
The INT and QUIT signals are ignored for a command executing in the background while the monitor option is unset.
trap commands signals When a signal is received execute the commands (which could be a function name)
See /usr/include/sys/iso/signal_iso.h for list of signals
end_program ()
{
rm $TMPFILE # delete temporary file if user types Ctrl-C
exit 1
}
trap end_program HUP INT QUIT TERM
Options
Use + to turn these options back off.
set -A NAME arguments Array assignment, assigning sequential values from arguments
set -a All subsequently defined variables are exported automatically
set -C noclobber. Prevents existing files from being overwritten by redirection
set -n Read commands in the script without executing them
set -x Prints commands and arguments as the are executed (debugging)