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?
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?
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".
Three things to remember while accessing an element in an index array:
arr=(one two three)
element_0="${arr[0]}"
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
arr=(100 150 350)
((sum_of_first_two = arr[0] + arr[1])) # no need for '{ }'
Although your actual problem was different from what the question title indicates (your approach to accessing the array item was correct), here are some general remarks on how to work with bash arrays.
From the Bash Reference Manual
Any element of an array may be referenced using
${name[subscript]}
. The braces are required to avoid conflicts with the shell’s filename expansion operators.
...
The subscript is treated as an arithmetic expression that must evaluate to a number.
This implies that no $
is necessary in the subscript.
If the subscript used to reference an element of an indexed array evaluates to a number less than zero, it is interpreted as relative to one greater than the maximum index of the array, so negative indices count back from the end of the array, and an index of -1 refers to the last element.
E.g.:
declare -i i=1 # -i declares integer
${arr[i*2]}
${arr[-1]} #returns last element
${arr[0]} #first element is at index 0
$
-style dereferencing of the array index. Please edit your answer to clarify its scope.
$
indexing I still thought it important to mention.
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.