2

I'm having problems working with an array in BASH. I've simplified the problem down to the following code:

#! /bin/bash

A1[0]="user1 user2 user3" 
A1[1]="user4 user5 user6"

for each in ${!A1[*]} 
do
        echo -n "$each "
        echo $A1[$each] 
done

The output is as follows:

0 user1 user2 user3[0]
1 user1 user2 user3[1]

I can't understand why each line has the [X] in it (presumably an indication of the element of the array). How can I recover both the index and the data line from the array without the index appended to it ?

  • 4
    You need braces. Try echo ${A1[$each]}. – Mikel Jun 8 '15 at 1:32
  • Thank you for this - it was spot on. If you put it as an answer I'll upvote and accept it. – davidgo Jun 8 '15 at 1:49
  • welcome. Answer posted. – Mikel Jun 8 '15 at 2:15
3

In bash*, you have to use braces like this:

echo ${A1[$each]}

to make [$each] a subscript into the A1 array.

Per man bash(1):

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion.

Further down, it says:

Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0.

Which is why your original code didn't work, since the shell only sees the subscript if you use braces.

So

echo $A1[$each]

is equivalent to

echo ${A1[0]}[$each]

where the square brackets don't have any special meaning, so are printed as-is.

  • And in ksh, and in zsh if the KSH_ARRAYS option is set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.