Home > OS >  Why is ${1[@]} invalid, even though ${stringVar[@]} works otherwise?
Why is ${1[@]} invalid, even though ${stringVar[@]} works otherwise?

Time:12-15

function HelloWorld()
{
var1=$1
echo ${var1[@]}

echo $1
echo ${1[@]}

}

HelloWorld "Hello World"

echo ${var1[@]} will run without issues but echo ${1[@]} gives me 'bad substitution.' I am not understanding the difference between these two cmds if var1 is the same as $1?

CodePudding user response:

${array[@]} is syntax that's only meaningful for arrays; a regular string can act like an array of length 1, but that syntax isn't implemented for positional parameters because there's no reason for it to be: Because a positional parameter cannot be an array, there is no possible valid, useful meaning "${1[@]}" could have as distinct from the meaning of "$1" or "${1}".

Being parsimonious with syntax extensions leaves currently-invalid syntax available for future extensions to give meaning to; if bash had defined meanings for all possible syntax, there would be no way to implement new extensions without breaking backwards compatibility. It is thus good language design[1] to avoid defining syntax that has no valid use.

[1] - Three words rarely used in that order to refer to bash!

  • Related