Is there any difference between $@
and "$@"
?
I understand there may be differences for non special characters, but what about the @
sign with input arguments?
$* Stores all the arguments that were entered on the command line ($1 $2 ...). "$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...).
$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.
The $@ holds list of all arguments passed to the script. The $* holds list of all arguments passed to the script.
Passing $@ to a command passes all arguments to the command. If an argument contains a space the command would see that argument as two separate ones.
Passing "$@" to a command passes all arguments as quoted strings to the command. The command will see an argument containing whitespace as a single argument containing whitespace.
To easily visualize the difference write a function that prints all 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 "$@"
Calling that script with
<script> "foo bar"
will produce the output
#### testing with $@ ####
argument: 'foo'
argument: 'bar'
#### testing with "$@" ####
argument: 'foo bar'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With