Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the array name without an index gets the first array element in Bash, ok?

Tags:

arrays

bash

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
like image 580
Buoy Avatar asked Oct 20 '25 19:10

Buoy


1 Answers

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.

like image 163
Barmar Avatar answered Oct 23 '25 09:10

Barmar