2
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?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 3
    `$1` cannot be an array; it can only ever possibly be a single string. – Charles Duffy Dec 14 '21 at 00:37
  • BTW, re: the `function` keyword, see https://wiki.bash-hackers.org/scripting/obsolete; the right way to define a function is just `HelloWorld() {` with no preceding `function`. – Charles Duffy Dec 14 '21 at 00:38
  • Another aside: [I just assigned a variable, but `echo $variable` shows something different!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) -- always `echo "$1"`, not `echo $1`; and `echo "${var1[@]}"`, not `echo ${var1[@]}`. Otherwise you get unwelcome surprises (`HelloWorld '* HOORAY *'` replacing the `*`s with lists of filenames, f/e; or changing tabs and newlines to spaces; and so forth). – Charles Duffy Dec 14 '21 at 00:40
  • 1
    @CharlesDuffy : Correct, but IMO it's only half of the truth, because `var1` in that example isn't an array either. However, indexing a scalar with `[@]` or `[0]` is allowed and just gives us back that element. I believe that the real reason is, that indexing is **syntactically** allowed only on variables, and variables in bash must start with a letter or underscore, with the exception of the few well known special variables (`$1`, `$-` etc). The designers of bash could have allowed `${1[...]}` for orthogonality, but they decided against it. – user1934428 Dec 14 '21 at 07:08

1 Answers1

2

${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!

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441