Tuesday, January 23, 2007

Array in Shell Script - Shell Beginner


Some of the important operations with array in BASH.

$ cat array.sh
#!/bin/sh

array=(jerry gen glan rahim)
len=${#array[*]} #Number of elements of the array

echo "The array has $len members. They are:"

i=0
while [ $i -lt $len ]; do
echo "$i: ${array[$i]}"
let i++
done

#Some operations
echo "Adding "jack" to the end of the array"
array=( "${array[@]}" "jack" )
echo "Listng all the elements in the array"
echo "${array[@]}"
echo "Listng all the elements in the array"
echo "${array[*]}" #One more way
echo "Deleting \"gen\""
unset array[1] #Same as array[1]=
echo "Now the array is"
echo "${array[@]}"
echo "length of 3rd element in the array"
len1=${#array[2]}; echo $len
echo "Deleting the whole array"
unset array
echo "${array[@]}" #Array is empty

$ ./array.sh
The array has 4 members. They are:
0: jerry
1: gen
2: glan
3: rahim
Adding jack to the end of the array
Listng all the elements in the array
jerry gen glan rahim jack
Listng all the elements in the array
jerry gen glan rahim jack
Deleting "gen"
Now the array is
jerry glan rahim jack
length of 3rd element in the array
4
Deleting the whole array

A more about Array of BASH can be found here:
http://tldp.org/LDP/abs/html/arrays.html

No comments:

© Jadu Saikia www.UNIXCL.com