Skip to content
Incomplete sheet

This sheet is incomplete and could use some attention. Please submit code snippet suggestions as an issue or PR here.

Korn shell

https://en.wikipedia.org/wiki/KornShell

Details Notes:

  • Start script with: #!/bin/ksh
  • Enable executation for file by running chmod u+x script.sh

Command-line argument parsing

Action Code Details
Program name, including the path if started from another directory
$0
Number of arguments
$#
Get the _n_th argument
$n
Get the _n_th argument, with default value
${n-"Default value here"}
Expand all arguments to a single word
$*
Expand all arguments to single string
$@
Expand arguments to separate words
"$@"

Test

Action Code Details
Check for zero arguments
if [[ $# -eq 0 ]];then
    print "No Arguments"
    exit
fi

Special variables

Note that the positional parameters are special variables too.

Action Code Details
Exit status of last command
$?
Process id of current program
$$
Process id of last background job
$!

Constants

Action Code Details
Declare constant
declare -r PASSWD_FILE=/etc/passwd

Variables

  • Don't put dots in variable names!
  • By default, all variables are global! Even within functions!
Action Code Details
Get variable value
$var
Get variable value with default value value
${var:-value}
Get variable value but throw error if not set
${var:?"Error! var not set!"}
Get variable and set it with default value if it is not set
${var:=value}
Check if variable is set
${var:+1}
Returns 1 if set, else nothing
Set value for variable
var=value
Set value from user input
read var
Set command output for variable
var=command args
Declare local variable
typeset var
Set local variable
typeset var = value

Functions

Use the local statement to define local variables.

Action Code Details
Define function
function get_name {
    return $name
}
Define function with arguments
function increment {
    local x = $1
    return (( $x + 1 ))
}
Call function
foo
Call function with arguments
foo arg1 arg2

Control flows

See http://www.bolthole.com/solaris/ksh-basics.html

Action Code Details
Chain (pipe) commands
command1 | command2 | command3
If
if [[ $value -eq 2 ]];then
    print "$value is 2"
fi
If-else
if [[ $value -eq 2 ]];then
    print "$value is 2"
else
    print "$value is not 2"
fi
If-elseif
if [[ $status -eq 200 ]];then
    print "OK (status = 200)"
elif [[ $value -gt 400 ]];then
    print "Error (status > 400)"
else
    print "Not 200 but < 400"
fi
Switch
case $food in
    apple|pear) print "fruit";;
    onion)  print "veggy";;
    *)  print "unknown";;
esac
Cases don't fall through, unless ;& is used instead of ;; Strings can be matched using wildcards.
For
for f in $(ls);do
    (( count += 1 ))
done
print "Total: $count"
Use continue to skip the loop. Use break to exit the loop.
Until
until [[ $stopnow -eq 1 ]] ; do
    echo just run this once
    stopnow=1;
    echo we should not be here again.
done
Pause for n seconds
sleep n

Error handling

Action Code Details
Throw error and stop execution, with unspecified error
exit 1
Throw error with message
echo "Error!" 1>&2
exit 2
Run command only if the former command succeeds
command1 && command2
Run command only if the former command fails
command1 || command2
Run (cleanup) function on error
trap cleanup ERR
For a previously defined cleanup function
Run code on error
trap "echo Oh no!" ERR
Run code on interupt
trap "echo Oh no!" INT
e.g., when user presses Ctrl+C
Run code on error or interrupt
trap "echo Oh no!" ERR INT
Run code on process termination
trap "echo Oh no!" TERM

Number handling

Action Code Details
Increment variable
(( count += 1))
Increment variable
let count += 1
Sum variables
sum = $(( a + b ))
Equals number num
$count -eq num
Not equals number num
$count -ne num
Greater than number num
$value -gt num
Less than number num
$value -lt num

String handling

Action Code Details
Equals string str
$name = "str"
Not equals string str
$name != "str"

Path handling

Action Code Details
Get parent path
${name%/*}
Get filename from path
${name##*/}

Output

Action Code Details
Print message
echo "Hello world!"
Print variable
echo $var
Formatted printing
printf "counting %d days" $days

Data redirection

Action Code Details
Write to new file or overwrite file
command > file
Append file
command >> file
Redirect error output
command 2> file
Discard errors
command 2>/dev/null
Redirect to normal output
command 2>&1
Discard all output
command > /dev/null 2>&1
File as input to command
command < file

Filesystem handling

Action Code Details
Check if directory exists
[ -d "$DIRPATH" ]
Check if directory is missing
[ ! -d "$DIRPATH" ]
Create directory
mkdir "$DIRPATH"
Check if file exists
[ -f "$FILEPATH" ]
Count the number of files in a directory
count=find $dir -maxdepth 1 -name "*.txt" -type f | wc -l