Tuesday, September 27, 2011

Shell Script: Find number of elements in an array

shell (bash) provides one-dimensional array variables. Any variable may be used as an array and there is no maximum limit on the size of an array. Below is the way to find length of array in shell script.

#!/bin/bash
SERVERS=(SERVER1 SERVER2 SERVER3 SERVER4)
# set length of an array
arrayLength=${#SERVERS[*]}
# or
#arrayLength=${#SERVERS[@]}
#Traverse each entry for (( i=0; i<${arrayLength}; i++ )); do   echo ${SERVERS[$i]} done

No comments: