Program name, including the path if started from another directory
$0
Number of arguments
$#
Check for zero arguments
if [[ $# -eq 0 ]];then print "No Arguments" exit fi
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
"$@"
Special variables
Note that the positional parameters are special variables too. | What | How | Details | |—|—|—| | Exit status of last command | $? | | | Process id of current program | $$ | | | Process id of last background job | $! | |
Constants
What
How
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!
What
How
Details
Get variable value
$var
Get variable value with default value value
${var:-value}
Get variable and set it with default value if it is not set
${var:=value}
Get variable value but throw error if not set
${var:?"Error! var not set!"}
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.
What
How
Details
Define function
function foo { return $name }
Define function with arguments
function foo { typeset a = $1 return $a }
Call function
foo
Call function with arguments
foo arg1 arg2
Control flows
See http://www.bolthole.com/solaris/ksh-basics.html
What
How
Details
Chain (pipe) commands
command1 | command2 | command3
If
if [[ $value -eq 7 ]];then print "$value is 7" fi
If-else
if [[ $value -eq 7 ]];then print "$value is 7" else print "$value is not 7" fi
If-elseif
if [[ $value -eq 7 ]];then print "$value is 7" elif [[ $value -eq 8 ]];then print "$value is not 7 but 8" else print "$value is neither 7 or 8" fi
Switch
case $var in john|fred) print $invitation;; martin) print $declination;; *) print "Wrong name...";; esac
There is no “fall through” with ;;. You hit only one set of commands.. UNLESS you use “;&” instead of “;;’. You can use WILDCARDS to match strings.
For
for foo in $(ls);do print "\$count is $count" (( count -= 1 )) done | Use continue to skip the loop. Use break` to exit the loop.