-2

I found the following snippet of bash script from How can I run a function from a script in command line?

$ cat test.sh
testA() {
  echo "TEST A $1";
}

testB() {
  echo "TEST B $2";
}

"$@"

This works well. One of the response of this answer is Use "$@" in most cases. $@ is not safe in some cases

I'm wondering why $@ needs quotation marks, "$@" , in the last line. What makes it difference with or without quotation marks around $@ in the bash script?

user2761895
  • 1,431
  • 4
  • 22
  • 38

1 Answers1

0

"$@" quotes each positional paremeter that is expanded. For example:

# script.sh
cat "$@"
cat $@

If you do script "a b" the first cat will try to emit a file literally named a b. Since the positional parameters aren't quoted for the second cat, it will try to emit individual files named a and b. This can cause all kinds of problems since the user quoted the value passed to script and expected it to be handled as one word/unit.

Note that "$@" is a bit special since if you do script "a b" "c d" this expands to: cat "a b" "c d" in the script rather than cat "a b c d". The second line would do cat a b c d which tries to concatenate four different files rather than two files with spaces in the name.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 1
    It's worth noting that `cat $@` behaves identically to `cat $*` -- it's only with quotes in place that there's any distinction in behavior between the constructs. – Charles Duffy Jan 08 '18 at 18:56
  • (Also, you might consider an example that can be expanded to include globs to demonstrate that behavior as well as string-splitting -- ie. `./script '* READ ME FIRST *.txt'`, in which case either `$@` or `$*` unquoted will replace the `*` and `*.txt` with lists of files in the current directory). – Charles Duffy Jan 08 '18 at 19:01
  • @CharlesDuffy thanks; I'll leave your comment as an example of that. I really just wanted to illustrate the difference in general and indicate that it can be dangerous or cause unexpected behavior. That could really be anything including security issues. – Explosion Pills Jan 08 '18 at 19:04