Korn Shell Programming Cheat Sheet: Special Characters
Korn Shell Programming Cheat Sheet: Special Characters
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
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)
Execution
If a command name matches a built-in command, it is executed within the current shell process.
Otherwise, if a command name matches a user defined function, the function is executed within the current shell process.
Otherwise, a process is created and an attempt is made to execute the command using exec searching $PATH to find an
executable file if the filespec does not begin with a /. If the file has the execute permission bit set, but the file is not an
executable program, it is assumed to be a text file containing shell commands and a sub-shell is spawned to read it. The
sub-shell does not include non-exported aliases, functions and variables. However, a parenthesized command is executed
in a sub-shell that includes the current environment.
. file params Read the complete file, then execute the commands within the current shell environment.
$PATH is used if necessary to find the file.
alias -x name=value Create an alias for a command. Eg. alias ll=”ls -al”
-x exports the alias to scripts invoked by name
for NAME in $LIST; do Each time through the loop, the next word of LIST is assigned to NAME
commands
done
while commands; do while [ expression ]; do Loop as long as the last of the commands return a status of 0
more commands
done
until commands; do Loop as long as the last of the commands returns a status of non-zero
more commands
done
case $NAME in
pattern) commands ;;
pattern) commands ;;
*) commands ;; #default if no previous patterns matched
esac
Filename Expansion
* Matches any string, including null
? Matches any single character
[...] Matches any single character in this list [a-d] is the same as [abcd]
[!...] Matches any single character not in this list
Positional Parameters
$0 The command itself
$1 First parameter $2 is 2nd, etc.
$* All the parameters $1 $2 etc. If within double quotes a single word is generated with a space
between each parameter
$@ All parameters $1 $2 etc. If within double quotes, each parameter expands to a separate word
$# A decimal value which is the number of parameters (including the command parameter)
$? The value of the exit status of the last executed foreground command. 0 is true.
$$ The process ID of the shell
$! The process ID of the last background command
shift Positional parameters are moved so $1=$2 $2=$3 etc
shift number Positional parameters are shifted by the number specified (less than or equal to $#)
Named Variables
$NAME
${NAME} Equivalent, but needed if following characters are legal in as a name
If a named parameter is exported, it becomes an Environment Variable and is available to programs spawned.
Modification of Variables
${NAME:-word} If NAME is unset or null, word is used instead
${NAME:=word} If NAME is unset or null, word is assigned to NAME and used (does not work for $1 $2 etc.)
${NAME:?} If NAME is unset or null an error message is sent to stderr
${NAME:+word} If NAME is unset or null, the null string is used, otherwise word is used
If the colon is omitted from the above the test is only for NAME being unset
Variable Expansion
If expansion occurs within double quotes, pathname expansion and field splitting is not performed on the result.
suffix and prefix are subject to tilde expansion, parameter expansion, command substitution and arithmetic expansion.
${#NAME} The number of characters in NAME
${NAME%suffix} Strip the smallest suffix from NAME before using it (eg. remove filename extension)
${NAME%%suffix} Strip the largest suffix from NAME before using it
${NAME#prefix} Strip the smallest prefix from NAME before using it
${NAME##prefix} Strip the largest prefix from NAME before using it
~logname/filepath Substutes ~logname for the home directory ie. /export/home/logname/filepath
If logname is omitted, the $HOME environment variable is used
${NAME[element]} Use the value of an array variable. Element can be an arithmetic expression.
Arrays
Set -A NAME John David Smith equivalent to NAME[0]=John ; NAME[1]=David; NAME[2]=Smith
echo ${NAME[*]} equivalent to echo ${NAME[0]} ${NAME[1]} ${NAME[2]}
Conditional Expressions
Used to test file attributes and compare strings.
(expression) true if expression is true. Used to group expressions.
! expression true if expression is false
test expression Evaluates conditional expressions - old Bourne syntax – use [[ ]] or (( ))
exp1 && exp2 true if both expressions are true
exp1 || exp2 true if either expression is true
(( exp1 == exp2 )) true if the expressions are equal Need spaces around brackets
(( exp1 != exp2 )) true if the expressions are not equal
(( exp1 < exp2 )) true if exp1 is less than exp2
(( exp1 <= exp2 )) true if exp1 is less than or equal to exp2
(( exp1 > exp2 )) true if exp1 is greater than exp2
(( exp1 >= exp2 )) true if exp1 is greater than or equal to exp2
Arithmetic Expressions
Expressions can be used when assigning an integer variable, as numeric arguments to test, and with let to assign a
value to a variable. Use () to override precedence.
unary minus == equals
! logical not !- not equals
* multiply < less than
/ divide <= less than or equal
% modulus > greater than
+ add >= greater than or equal
subtract
let A=B*C assign A as the product of B times C
typeset -i A create integer variable A
Arithmetic Evaluation
let performs integer arithmetic using long integers.
Constants may be in another base as base#value, so 16#20 is 0x20 which is decimal 32.
Precedence and associativity of operators are the same as C language.
Parameter substitution syntax is not used to reference variables.
Shell Initialization
Note: Common to bourne shell initialization also, so commands must be compatible with both, or test $0 for the shell
/etc/profile common to all users
$HOME/.profile specific to each user
$ENV run on each invocation of an interactive shell eg. ENV=$HOME/.kshrc