Chap 16
Chap 16
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.
$ 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
$ 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
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[*]}
#set a counter to the base index #measure the length of the array
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