You are on page 1of 8

Array variables

An array variable •can be used to store multiple values •is one-dimensional •can hold up to 1024 elements (in the range 0 – 1023) The contents of an array variable is assigned using the syntax:

$ varname[integer]=value
The contents of an array variable can be viewed by using the syntax:

$ echo ${varname[integer]}
Where integer is the number, in the range 0 – 1023, of the element to view.

Substituting & Counting All Elements
•The entire contents of an array variable can be viewed using the syntax:

$ echo ${varname[*]}
where the * character represents the value: ALL ELEMENTS

•The number of elements being used can be displayed using the syntax:

$ echo ${#varname[*]}
This syntax is interpreted as # (number of) * (all elements) of variable varname

Using Integer Variables as Element Numbers
An integer variable can be used instead of a literal number.

$ echo ${varname[x]}
There is no requirement to use $x because an element identifier would always be an integer value. The variable x, must contain an integer variable. Example:

#!/bin/ksh

typeset –i x=0
while (( x < ${#varname[*]} ))

do
echo ${varname[x]) (( x = x + 1 )) done

The index value of an array may be used to perform arithmetic evaluations. The index is treated as ((expression)) and is processed before the value of the array variable is accessed. Example:
index=5 array[index+1]=“Hello World”

echo ${array[6]}
IMPORTANT: To use array, shift to Korn shell. $ksh <enter>

Initializing an array
It is not necessary to initialize array. There are, however, some instances when this would be desirable. Consider the following example:

unset –v arr

#remove the variable if it
#exists

arr[1]=10

arr[2]=33
arr[3]=84

echo ${arr[*]} 10 33 84

It is not necessary to use a loop to initialize an array. The array may be initialized by using the set command. Syntax:

set –A array v1 v2 v3 v4 v5 v6 …
In which: -A array v1-vn In which: +A -Does not initialize a new variable, but modifies an existing one -Initializes a new variable (overwrites it exists) -Is the name for the array -Are the values for the array, starting with index 0

#!/bin/ksh
set –A arr are we having fun yet echo ${arr[*]} #display the contents of the array #output: are we having fun yet

echo ${#arr[*]}

#display the element count in the array
#output: 5

index=0 length=${#arr[*]} while

#set a counter to the base index #measure the length of the array

(( index < length )) do

echo “Element $index is: ${arr[index]}”
(( index+=1 )) done

Exercise
• Create a script called s1 that prompts the user to enter a sentence, store the sentence word-byword into an array, then print the sentence to the screen in reverse order. • Create a script called s2 that converts decimal number into binary. The number is a parameter to the command s2. IMPORTANT: Always start your script with the line #!/bin/ksh