Understanding Korn Shell Arrays

Korn Shell Arrays

Arrays are variables that contain more than one value. Don’t declare arrays explicitly or explicitly set an array size. An array is created when you first use it. It is treated as an array when you first assign a value to one element of the array variable. Each array can hold up to 1024 values.

You can create arrays of strings or integers. By default, an array contains strings. To create an array of integers, declare a variable as an integer, and then use it as an array by assigning integer values to the elements; for example:

integer my_array
my_array[1]=5
my_array[12]=16

The first element of an array is indexed by 0, the second element is indexed by 1, and so on. Therefore, the largest index value that is valid is 4095. All arrays in the Korn shell are one-dimensional arrays. Enclose an array reference in braces for the Korn shell to recognize it as an array. For example use ${arr[1]} instead of $arr[1].

The syntax for accessing the value of the ith array element is the following, where i is an integer:

{array_name[i]}

To print the values of all array elements, use the syntax:

{array_name[*]}

To print the number of elements (assigned values) in the array, use the syntax:

{#array_name[*]}

You don’t have to assign array elements in order or assign values to any elements. Skipped array elements are not assigned a value and are treated as though they do not exist.

arr[2]=two
arr[4]=4
arr[8]=eight
arr[16]=16

Examples of Using Arrays

The first two of the following examples illustrate how to create arrays of strings. You do not need to enclose the values assigned to the various array elements within double quotes unless the string value contains special characters, such as spaces or tabs.

To create an array of three strings:

$ arr[0]=big
$ arr[1]=small
$ arr[2]="medium sized"

To create an array of three strings using the set statement:

$ set -A arr big small "medium sized"

Note: Not all Korn shell implementations support the set -A statement.

In the following examples, note the creation of the array of integers. The variable num is first declared as an integer variable and then it is used as the name of an array to assign integers to the first five elements of the array. If you try to assign a value other than an integer to any of the elements of the array, you get a bad number error message. To create an array of five integers:

$ integer num
$ num[0]=0
$ num[1]=100
$ num[2]=200
$ num[3]=300
$ num[4]=400

To print the number of array elements in the num array:

$ print ${#num[*]}
5

To print the values of all array elements in the arr array:

$ print ${arr[*]}
big small medium sized

To unset the arr array:

$ unset arr
    Closure (*)4-13
    Closure (*)4-13