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]}
Special variables
There are some "special" variables that ksh itself gives values to. Here
are the ones I find interesting
- PWD - always the current directory
- RANDOM - a different number every time you access it
- $$ - the current process id (of the script, not the user's shell)
- PPID - the "parent process"s ID. (BUT NOT ALWAYS, FOR FUNCTIONS)
- $? - exit status of last command run by the script
- PS1 - your "prompt". "PS1='$PWD:> '" is interesting.
- $1 to $9 - arguments 1 to 9 passed to your script or function (you
can actually have higher, but you need to use braces for those)
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}
TOP of tutorial
Next: POSIX.1 utilities: Externally usable
tools on most UNIXen.
Prev: Ksh Basics
This material is copyrighted by Philip Brown