When I type this in bash command line
$ x=hi; printf '%s ' "$x" "${x[0]}"; echo "${_[0]}"
I have this output:
hi hi hi
- Why
"${_[0]}"
turns out to be"hi"
in the output?
- Why could we use the
"x[0]"
syntax, given that"x"
is just astring
instead of anarray
?
Best Answer
The
_
parameter has several meanings depending on context, but it is never an array. Likewise, in your example,x
is not an array. The reason you're able to treat it as if it is an array is that Bash allows non-array variables to be treated as if they were one-element arrays. Bash likewise allows array variables to be treated as if they were non-arrays, giving the first element.As
man bash
says:So
"${_[0]}"
behaves the same as"${_}"
or"$_"
, because_
is not an array. Likewise,"${x[0]}"
behaves the same as"${x}"
or"$x"
, becausex
is not an array.As for why
_
holds the valuehi
: In the usage you've shown, performing parameter expansion on the special_
parameter yields the last argument of the most recent (synchronously executed) command.As
man bash
says of_
:(emphasis mine)
In this case, the most recently executed command was:
The arguments passed to
printf
were:%s
, on which only quote removal was performed.hi
, on which parameter expansion was performed, followed by quote removal.hi
, on which a more complex form of parameter expansion yielding the same result was performed, followed by quote removal.