The more useful functions in ksh I find are:
will set the variableread varname
varname
to have the value of the next
line read in from standard input.
What often comes next, is
This sets the argument variables $1, $2, etc to be set as if the program were called with $varname as the argument string to the shellscript. So, if the value of varname is "first second third", then $1="first", $2="second", and $3="third".set $varname
Note that if you want to access "double-digit" arguments, you cannot use "$10". it will get interpreted as "$1,""0". To access argument #10 and higher you must explicitly define the limits of the variable string, with braces:
echo ${10}This is also good to know, if you wish to follow a variable immediately followed by a string. Compare the output from the following lines:
a="A " echo $astring echo ${a}string
if [[ $? -ne 0 ]] ; then echo status is bad ; fi if [[ "$var" != "good" ]] ; then echo var is not good ; fi if [[ ! -f /file/name ]] ; then echo /file/name is not there ; fi if [[ ! -d /dir/name ]] ; then echo /dir/name is not a directory ; fi
Please note that [[]] is a special built-in version of test, that is almost, but not 100%, like the standard []. The main difference being that wildcard expansion does not work within [[]].
The math evaluator is very useful. Everything inside the double-parens gets evaluated with basic math functions. For example;
four=$((2 + 2)) eight=$(($four + 4)) print $(($four * $eight))
Warning: Some versions of ksh allow you to use floating point with $(()). Most do NOT.
Also, be wary of assumptions. Being "built in" is not always faster than an external progam. For example, it is trivial to write a shell-only equivalent of the trivial awk usage, "awk '{print $2}'", to print the second column. However, compare them on a long file:
# function to emulate awk '{print $2}' sh_awk(){ while read one two three ; do print $two done } # and now, compare the speed of the two methods time sh_awk </usr/dict/words >/dev/null time awk '{print $2}' </usr/dict/words >/dev/null
The awk version will be much much faster. This is because ksh scripts are interpreted, each and every time it executes a line. AWK, however, loads up its programming in one go, and figures out what it is doing ONE TIME. Once that overhead has been put aside, it then can repeat its instructions very fast.