Advanced variable usage
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
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
This material is copyrighted by Philip Brown