Is there a difference between $@ and "$ @"?

Is there a difference between $@ and " $@ " ?

I understand that there may be differences for non-specific characters, but what about the @ sign with input arguments?

+6
source share
2 answers

Yes!

 $ cat a.sh echo " $@ " echo $@ 

Let run it:

 $ ./a.sh 2 "3 4" 5 2 3 4 5 # output for " $@ " 2 3 4 5 # output for $@ -> spaces are lost! 

As you can see, using $@ allows the parameters to “lose” some content when used as a parameter. See -for example- I just assigned a variable, but the echo $ variable shows something else for a detailed explanation of this.


From GNU Bash manual → 3.4.2 Special parameters :

@

($ @) Expands to positional parameters, starting with one. When expansion occurs in double quotes, each parameter is expanded to a single word . That is, "$ @" is equivalent to "$ 1" "$ 2" .... If a double-quotation extension occurs inside a word, the extension of the first parameter is connected to the initial part of the original word, and the extension of the last parameter is connected to the last part of the original word. When there are no positional parameters, expand "$ @" and $@ to zero (ie they are deleted).

+9
source

Passing the command $@ passes all the arguments to the command. If the argument contains a space, the command will see this argument as two separate.

Passing the $ @ command to the command passes all arguments as quoted strings to the command. The command will see the argument containing spaces as the only argument containing spaces.

To easily visualize the difference, write a function that prints all of its arguments in a loop, one at a time:

 #!/bin/bash loop_print() { while [[ $# -gt 0 ]]; do echo "argument: '$1'" shift done } echo "#### testing with \ $@ ####" loop_print $@ echo "#### testing with \"\ $@ \" ####" loop_print " $@ " 

Call script with

 <script> "foo bar" 

will produce output

 #### testing with $@ #### argument: 'foo' argument: 'bar' #### testing with " $@ " #### argument: 'foo bar' 
+5
source

All Articles