Advanced variable usage

Braces

Sometimes, you want to immediately follow a variable with a string. This can cause issues if you use the typical grammar of "echo $a" to use a variable, since ksh by default, attempts to do "intelligent" parsing of variable names, but it cannot read your mind.
Compare the difference in output in the following lines:
two=2
print one$twothree
print one${two}three
There is no variable named "twothree", so ksh defaults it to an empty value, for the first print line. However, when you use braces to explicitly show ksh {this is the variable name}, it understands that you want the variable named "two", to be expanded in the middle of those other letters.

Arrays

Yes, you CAN have arrays in ksh, unlike old bourne shell. The syntax is as follows:

# This is an OPTIONAL way to quickly null out prior values
set -A array
#
array[1]="one"
array[2]="two"
array[3]="three"
three=3

print ${array[1]}
print ${array[2]}
print ${array[3]}
print ${array[three]}  #This is interpreted as array[3]

Note that ksh automatically dereferences names inbetween [], to be variable values. Unfortunately, ksh does not seem to handle associative arrays. (storing values indexed by a string 'abcd', rather than a number index)

Special variables

There are some "special" variables that ksh itself gives values to. Here are the ones I find interesting

Tweaks with variables

Both bourne shell and KSH have lots of strange little tweaks you can do with the ${} operator.
The ones I like are below.


To give a default value if and ONLY if a variable is not already set, use this construct:


APP_DIR=${APP_DIR:-/usr/local/bin}


(KSH only)
You can also get funky, by running an actual command to generate the value. For example


DATESTRING=${DATESTRING:-$(date)}


(KSH only)
To count the number of characters contained in a variable string, use ${#varname}.


  echo num of chars in stringvar is ${#stringvar}


(KSH only)
To strip off characters from a variable's value, using shell wildcard matching:
(note that using the doubled-char, means "greedy match": match the longest you can. Whereas the single char default is to just snip off the first match)

$ PATHNAME=/path/to/file

$ print ${PATHNAME#*/}
path/to/file
$ print ${PATHNAME##*/}
file

$ print ${PATHNAME%/*}
/path/to
$ print ${PATHNAME%%/*}
(nothing! It stripped away the entire path! :)

The above is useful for shell-internal replacements for "dirname" and "basename" commands; however, the operators have other uses as well.


TOP of tutorial
Next: POSIX.1 utilities: Externally usable tools on most UNIXen. Prev: Ksh Basics
This material is copyrighted by Philip Brown