2

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?

9
  • 1
    @OliCharlesworth: I should have learned better than to argue with you after our last encounter! Still, I like bash. I like it a lot. Commented Mar 19, 2012 at 1:14
  • @thb: Each to their own! But IMO, any language that requires [ to be an executable in order to work is a language that sucks. Commented Mar 19, 2012 at 1:14
  • 1
    @OliCharlesworth: But [ isn't an executable, it's a builtin. (Granted, it's a deficient one -- the behavior of the [[ ... ]] notation is far superior -- but it's not as though changing your $PATH would suddenly break [.) Commented Mar 19, 2012 at 1:30
  • 1
    @violet313: [ and test are both builtins; neither is an alias for the other. They are equivalent in all respects, however, except that [ expects its last argument to be ] (which it discards). Commented Mar 19, 2012 at 1:40
  • 1
    @OliCharlesworth, instead of which [ try type -a [ Commented Mar 19, 2012 at 13:14

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

0

For the same reason A works: parameter expansion and substitution

1 Comment

Ok. I read that. I still don't get it. Suppose I use the following indirection: C=B; echo "${A[$C]}"; echo "${$C}" ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.