Tuesday, August 25, 2009

linux: creating and using arrays in shell scripts

Bash arrays have numbered indexes only, but they are sparse, i.e. you don't have to define all the indexes.

An entire array can be assigned by enclosing the array items in parenthesis:
arr=(Hello World)

Individual items can be assigned with the familiar array syntax (unless you're used to Basic or Fortran):
arr[0]=Hello
arr[1]=World


But it gets a bit ugly when you want to refer to an array item:
echo ${arr[0]} ${arr[1]}

To quote from the man page:

The braces are required to avoid conflicts with pathname expansion.

In addition the following funky constructs are available:
${arr[*]};  # All of the items in the array
${!arr[*]}; # All of the indexes in the array
${#arr[*]}; # Number of items in the array
${#arr[0]}; # Length of item zero

The ${!arr[*]} is a relatively new addition to bash, it was not part of the original array implementation.

source

No comments: