Reputation: 1932
I am new to bash-scripting & trying to understand how things work. It's all a bit strange..
The following can be put into a script or entered into the shell:
declare -a A=("foo" "bar")
B=1
[ ${A[B]} == ${A[$B]} ] && echo "wTF" || echo ";)"
This gives me "wTF" on my debian squeeze & also on cygwin 1.7.11-1
So. Why does ${A[B]}
work?
Upvotes: 2
Views: 166
Reputation: 183564
From the Bash Reference Manual, §6.7 "Arrays":
Indexed arrays are referenced using integers (including arithmetic expressions […]) and are zero-based; […] ¶ The subscript is treated as an arithmetic expression that must evaluate to a number greater than or equal to zero.
So in effect, ${A[B]}
means ${A[$((B))]}
. This is convenient when you want something like ${A[B-1]}
.
Arithmetic expressions are explained in §6.5 "Shell Arithmetic", which says in part:
Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.
So, $((B))
means $(($B))
(except that the former is smarter about some things, e.g. using zero instead of blank as a default for uninitialized variables).
Upvotes: 4
Reputation: 2650
For the same reason A
works: parameter expansion and substitution
Upvotes: 0