6

Whenever I'm writing a script (or function) that is supposed to "pass along" its arguments to some other downstream "callable" (binary, script, function, etc.) foo, I code this passing along of arguments like this

foo "$@"

...but I have also seen this alternative

foo "$@[@]"

I have tried, unsuccessfully (at least with zsh), to concoct scenarios in which these two approaches would produce different results.

Are they really synonymous? If not, when would one prefer one form over the other?


(I'm primarily interested in the case of zsh, which is my everyday shell, but at work I often need to write bash scripts, so I'd be curious about the answer to this question for bash as well.)

6

"$@" is a Bourne shell invention (1979). That's meant to expand to the list of positional parameters, as if you had typed "$1" "$2" "$3"....

When David Korn added array support in the early 80s, it extended that concept to arrays with the "${array[@]}" syntax. zsh also supports the "$array[@]" shorter form.

"$@" refers to the positional parameters (starting from $1), it's a bit like an array, but except in zsh or yash, not exactly. For one, $@ starts at index 1, while other arrays in ksh or bash start at 0. ${@[@]} won't work in ksh or bash.

The only shells where "${@[@]}" works are zsh and yash. zsh is the only one where "$@[@]" works. There's no point using it over the standard "$@". What could be more useful is something like say: "$@[1,3]" to get the first 3 positional parameters.

If the point is that you would like to use an array-like syntax, in zsh, you can use "$argv[@]" ($argv is an array that refers to the positional parameters, like in csh/tcsh/fish).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.