shell array :
shell use [] as array index. use ${a[1]} to get value
$ a[1]=1
$ echo ${a[1]}
1
error :
$ echo "$a[1]"
[1]
注意下面的方法在shell中是不可以的
$ cat 1.sh
#!/bin/ksh
i=1
a[1]="a"
echo "$a[$i]"
但是tcl数组是可以的
$ cat 2.exp
#!/opt/exp/bin/expect
set i "1"
set a(1) "a"
puts "$a($i)
set -A colorTable $cRed $cGreen $cYellow $cBlue $cFuchsia $cCyan $cWhite
----
tcl use () as array index. use $C(1) to get value
set C(1) 1
set a "$C(1)"
In ksh, arrays are simple arrays that indexed by a number. There is a limit to the size of the ksh array. Most systems support indices 0-4095. After that you will get a “subscript out of range” error.
In tcl, arrays are associative arrays. The index is a text string. (You can use numbers 0, 1, 2, etc., but tcl will just interpret it as text.) Associative arrays are much more powerful because you can map from one string to another, which is a very useful capability. (The entire C array in xcoolit utilizes this heavily.)
You can set up an entire array in ksh via ‘set –A <arrayName> <values…>’. For example:
set –A myArray a b c d e
will set myArray[0]=a myArray[1]=b …
tcl also has a similar capability via ‘array set <arrayName> { <key1> <value1> <key2> <value2> … }’
but we doesn’t utilize this capability anywhere in our tools.
For both ksh and tcl, you can set individual array items as you have already seen:
Ksh: myArray[<nx>]=<value>
Tcl: set myArray(<nx>) <value>
Similarly, you can unset array items for individual array elements or for the entire array:
Ksh: unset myArray[<nx>]
Ksh: unset myArray
Tcl: unset myArray(<nx>)
Tcl: unset myArray
In ksh, you can dump all array contents by using index ‘*’ (ex. ${myArray[*]}). You can dump the number of elements in the array via the ‘#’ (length) specifier along with index ‘*’ (ex. ${#myArray[*]}).
In tcl, you can dump all keys of an array via ‘array names’ (ex. foreach nx [array names myArray] { … } ). The ‘array names’ command also accepts an optional parameter to limit the returned keys to only those that match the pattern (ex. ‘array names myArray abc*’ to only match keys that start with abc).