Bash array

There are two types of variables in Bash, singular variable and array.
Bash arrays have numbered indexes only, but they are sparse, ie you don’t have to define all the indexes. It can be asigned as an entire array or individual component:

arrayA=(Hello World)
or
arrayA[0]=Hello
arrayA[1]=World

But it gets a bit ugly when you want to refer to an array item:

echo ${arrayA[0]} ${arrayA[1]}

To quote from the man page:

Some useful constructs are:

${arrayA[*]} # All of the items in the array
${!arrayA[*]} # All of the indexes in the array
${#arrayA[*]} # Number of items in the array
${#arrayA[0]} # Length of item zero

The following example shows some simple array usage.

#!/bin/bash
arrayB=(one two three four [5]=five)
n=${#arrayB[*]}
echo "Array size: ${#arrayB[*]} or $n"
echo "Array items:"
for item in ${arrayB[*]}
do
printf " %s\n" $item
done
echo "Array indexes:"
for index in ${!arrayB[*]}
do
printf " %d\n" $index
done
echo "Array items and indexes:"
for index in `seq 0 $n `
do
printf "%4d: %s\n" $index ${arrayB[$index]}
done

Running it produces the following output:

Array size: 5
Array items:
one
two
three
four
five
Array indexes:
0
1
2
3
5
Array items and indexes:
0: one
1: two
2: three
3: four
4:
5: five

Note ${array[*]} can replaced with ${array[@]}

#!/bin/bash
arrayC=("first item" "second item" "third" "item")
echo "Number of items in original array: ${#arrayC[*]}"
for ix in ${!arrayC[*]}
do
printf " %s\n" "${arrayC[$ix]}"
done
echo
arr=(${arrayC[*]})
echo "After unquoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
printf " %s\n" "${arr[$ix]}"
done
echo
arr=("${arrayC[*]}")
echo "After * quoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
printf " %s\n" "${arr[$ix]}"
done
echo
arr=("${arrayC[@]}")
echo "After @ quoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
printf " %s\n" "${arr[$ix]}"
done

When run it outputs:

Number of items in original array: 4
first item
second item
third
item

After unquoted expansion: 6
first
item
second
item
third
item

After * quoted expansion: 1
first item second item third item

After @ quoted expansion: 4
first item
second item
third
item

Nice link

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s