Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between $@ and "$@"? [duplicate]

Tags:

bash

expansion

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

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

like image 524
Carmellose Avatar asked May 10 '16 14:05

Carmellose


People also ask

What is the difference between $@ and $*?

$* 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" ...).

What does $@ mean in shell?

$@ 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.

What is $@ and $* in shell script?

• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.

What echo $@ Shows in Unix?

The $@ holds list of all arguments passed to the script. The $* holds list of all arguments passed to the script.


1 Answers

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'
like image 176
a.peganz Avatar answered Oct 07 '22 01:10

a.peganz