4

GNU Bash 4.4 seems forgiving when accessing the first element or only element of an array by using just the array name or accessing a variable with array syntax. Both ${var[0]} and ${var[@]} return "Value" when the variable var='Value'.

I can simplify my code by using one of the arrays as a variable when only a variable is needed. For this package I'm more concerned with it not braking with the next Bash update than with portability.

Is it safe to write code that accesses the first element of an array using variable syntax?

declare -a foo='Value'
declare -p var
declare -a var=([0]="Value")
echo ${foo}
Value
1
  • Better use standard "${var[0]}" to access first element. Commented Mar 26, 2018 at 21:50

2 Answers 2

6

This is a documented behavior:

Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0.

However, I recommend you still use the subscript, to make your code clearer.

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

Comments

0

I confirmed that it is documented as far back as bash 2.0 (Dec 31, 1996):

curl -sL https://ftpmirror.gnu.org/bash/bash-doc-2.0.tar.gz \
| tar -xz 'bash-doc-2.0/doc/bashref.html' --to-stdout \
| grep -F --after-context=1 'without a subscript'

Result:

Referencing an array variable without a subscript is equivalent to
referencing element zero.

I couldn't find it documented in the bash 1.14 documentation (Aug 29, 1996) found at https://ftpmirror.gnu.org/bash/. The behavior might exist in v1.14 (I didn't test) but it isn't documented as far as I could tell.

Comments

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.