Main Content

String, Integer, Array, Associative Array - ksh variables

Archive - Originally posted on "The Horse's Mouth" - 2008-05-30 08:28:34 - Graham Ellis

• In the Korn Shell, variables default to be being strings ...

$ r 26
kay=7
$ r 30
while (( $kay>3 )); do
echo $kay
kay=$kay-1
done;
7
7-1
7-1-1
7-1-1-1
$


• ... but you can declare them as integers.

$ integer kay
$ kay=7
$ kay=$kay-1
$ echo $kay
$ (( g = 8+8 ))
$ echo $g
16
$ h=8+8
$ echo $h
8+8


• Variables can also be arrays

• and even associative arrays (i.e. with named elements)

$ typeset -A stuffing
$ stuffing[turkey]=sage
$ stuffing[chicken]=onion
$ print ${stuffing[turkey]}
sage
$


You can get out the keys and the values to iterate through them ...

typeset -A places
places[Bristol]="Temple_Meads"
places[Radstock]="Shut_Doen"
print ${places[Bristol]}
print ${places[Radstock]}
# Values
print ${places[*]}
# keys
print ${!places[*]}