Sunday, June 8, 2008

Using array in bash script


An example to illustrate the use of arrays in bash scripting.


#!/bin/sh
#Bash array implementation

array=(bash ksh csh)
len=${#array[*]} #Num elements in array

echo "Array has $len members.They are:"

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

#Some operations
echo "Adding \"zsh\" to the end of the array"
array=( "${array[@]}" "zsh" )
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 \"ksh\""
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


Executing:


$ ./basharray.sh
Array has 3 members.They are:
0: bash
1: ksh
2: csh
Adding "zsh" to the end of the array
Listng all the elements in the array
bash ksh csh zsh
Listng all the elements in the array
bash ksh csh zsh
Deleting "ksh"
Now the array is
bash csh zsh
length of 3rd element in the array
3
Deleting the whole array



A null/empty array in bash can be declared as (array initialization)


array=()


So you came to know the followings:


- How to initialize an array
- How to add an element to an array
- How to delete a particular element in the array or to delete the whole array.
- How to find the length of an element in an array or length of the whole array.


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

1 comment:

Unknown said...

Hi Jadu,

Do you happen to know why the array starts looping with the second value of the array? and it also looks like it iterates the 2nd value twice, and I don't know how to resolve this.

© Jadu Saikia www.UNIXCL.com