$@

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search

$@ is one of the Bash special parameters. It can only be referenced as follows

echo "$@"

However, assignment to it is not allowed:

@=foo

Purpose

$@ expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" .. "$n". If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Examples

Create a shell script called testpara.sh:

#!/bin/bash
echo "\$@ with double quotes : $@"
echo \$@ without double quotes : $@
echo
 
echo "\$@ with double quotes \$1 is : $1"
echo "\$@ with double quotes \$2 is : $2"
echo "\$@ with double quotes \$3 is : $3"
echo
 
echo \$@ without double quotes \$1 is : $1
echo \$@ without double quotes \$2 is : $2
echo \$@ without double quotes \$3 is : $3
echo

Run it as follows:

chmod +x testpara.sh
./testpara.sh one two three four

Sample outputs:

$@ with double quotes : one two three four
$@ without double quotes : one two three four

$@ with double quotes $1 is : one
$@ with double quotes $2 is : two
$@ with double quotes $3 is : three

$@ without double quotes $1 is : one
$@ without double quotes $2 is : two
$@ without double quotes $3 is : three

Now run it again as follows (note the double quotes when calling the script):

./testpara.sh one two "three four"

Sample outputs:

$@ with double quotes : one two three four
$@ without double quotes : one two three four

$@ with double quotes $1 is : one
$@ with double quotes $2 is : two
$@ with double quotes $3 is : three four

$@ without double quotes $1 is : one
$@ without double quotes $2 is : two
$@ without double quotes $3 is : three four

Consider the following for loop example (testpara1.sh):

#!/bin/bash
echo "*** Processing \$@ without double quote:"
for f in $@
do
	echo "\$f = $f"
done
 
echo "*** Processing \$@ with double quote:"
for f in "$@"
do
	echo "\$f = $f"
done

Save and close the file. Run it as follows:

chmod +x testpara1.sh
./testpara.sh1 one two "three four"

Sample outputs:

*** Processing $@ without double quote:
$f = one
$f = two
$f = three
$f = four
*** Processing $@ with double quote:
$f = one
$f = two
$f = three four