Unexpected output when accessing array element

5,864

Solution 1

a=('1' '2') && echo "${a[0]}" would be better like this.

In your version you only created a one element array which contains the value "1,2".

Solution 2

Three things to remember while accessing an element in an index array:

1. Normal expression - hardcoded index

arr=(one two three)
element_0="${arr[0]}"

2. Normal expression - index stored in a variable

arr=(it is cool to write readable code)
for ((i=0; i < ${#arr[@]}; i++)); do
    current_element=${arr[i]} # note, no '$' necessary before i
done

3. Arithmetic expression involving array elements

arr=(100 150 350)
((sum_of_first_two = arr[0] + arr[1])) # no need for '{ }'
Share:
5,864

Related videos on Youtube

Tommy
Author by

Tommy

Something for nothing. Bite me if you can score 9+ in a CPS Test.

Updated on September 18, 2022

Comments

  • Tommy
    Tommy almost 2 years

    I am using terminal with MacOSX.

    I read this entry introducing about unix array. I tried to access an array as its way, but failed:

    a=(1,2) && echo "${a[0]}"
    

    this is the output:

    1,2
    

    What I expected is 1.

    What should I do?

    • Timo
      Timo over 3 years
      On Zsh I get nothing output. As this is a bash question, it is maybe worth noting for ZSH users who came by accidentally.
  • chepner
    chepner almost 9 years
    The quotes aren't necessary, just the whitespace (not a comma) to create two items instead of one.
  • Roland
    Roland about 4 years
    @AdminBee The question asked is "How do I access an item of an array in shell?" which I answered.
  • Roland
    Roland about 4 years
    @AdminBee In spite of no one using $ indexing I still thought it important to mention.
  • Kusalananda
    Kusalananda about 4 years
    No, the issue is that the user gets 1,2 when expecting 1. You don't even mention why this is or what to do about it. Accessing the first element of the array is something the user is already doing correctly.
  • Roland
    Roland about 4 years
    @Kusalananda This was already answered by another poster. I arrived at this question by googling and found the answer I was looking for missing. codeforester provided some more details but didn't include everything. I tried to complete it. Btw neither does his answer mention the OP's problem.
  • Kusalananda
    Kusalananda about 4 years
    At least that answer shows how to assign to an array. Also, it would be easy for you to fix your answer and to make it relevant to the question.
  • Roland
    Roland about 4 years
    @Kusalananda Now that you edited the question my answer has indeed become unrelated to it. Moving the goalposts.
  • Kusalananda
    Kusalananda about 4 years
    @Roland I made the title relevant to the question. I never edited the text of the question, so the question remains the same.