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 '{ }'
Related videos on Youtube
![Tommy](https://lh3.googleusercontent.com/-DUshWzaXQHs/AAAAAAAAAAI/AAAAAAAADXw/4eCJN41Q1wQ/photo.jpg?sz=256)
Author by
Tommy
Something for nothing. Bite me if you can score 9+ in a CPS Test.
Updated on September 18, 2022Comments
-
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 over 3 yearsOn Zsh I get nothing output. As this is a bash question, it is maybe worth noting for ZSH users who came by accidentally.
-
-
chepner almost 9 yearsThe quotes aren't necessary, just the whitespace (not a comma) to create two items instead of one.
-
Roland about 4 years@AdminBee The question asked is "How do I access an item of an array in shell?" which I answered.
-
Roland about 4 years@AdminBee In spite of no one using
$
indexing I still thought it important to mention. -
Kusalananda about 4 yearsNo, the issue is that the user gets
1,2
when expecting1
. 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 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 about 4 yearsAt 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 about 4 years@Kusalananda Now that you edited the question my answer has indeed become unrelated to it. Moving the goalposts.
-
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.