How to Use $@ in Bash Scripting
Abstract: echo '3. With "$*"'arg 1 arg 2 arg 3 This is because "$*" considers all the positional parameters as a single word.
There are certain special variables that you will come across only in Bash. These variables might appear challenging at first. But, understanding how Bash uses these combinations of characters will help you move from an average Linux user to an experienced one.
In this guide, we learn about $@ special variable and how it is useful in Bash. We will see how it differs from $* variable.
2. What is Bash $@?$@ is an extremely simple yet powerful special parameter in Bash. Bash uses it to ease the passing and handling of positional parameters whether be it scripts or functions. Bash expands into the full list of positional arguments $1 $2 $3 … $n. It preserves the argument count through the expansion.
3. Difference between $@ and $*Without the use of double quotes, both $@ and $* have the same effect. All positional parameters from $1 to the last one used are expanded without any special handling.
When the $* parameter is double quoted, it expands to as:
"$1s$2s$3s……..$N"
's' is the first character of IFS. If IFS is unset, the parameters get separated by spaces. When IFS becomes null, the parameters join without the intervening separators.
But when the $@ special parameter is wrapped with double quotes, it is equivalent to:
"$1" "$2" "$3" ….. "$N"
This ensures all the positional parameters are the same as they were set initially and passed to the script or function. If we want to re-use these positional parameters to call another program, we should use double quoted "$@".
Now, let us practically interpret this with an example:
set -- "arg 1" "arg 2" "arg 3"
echo 1. 'With $*'
for word in $*; do echo "$word"; done
echo '2. With $@'
for word in $@; do echo "$word"; done
echo '3. With "$*"'
for word in "$*"; do echo "$word"; done
echo '4. With "$@"'
for word in "$@"; do echo "$word"; done

In this example we have considered four cases:
In the first two cases, the output will be as:
arg
1
arg
2
arg
3
This is because every argument, separated by a space, is considered a separate word.
The third case outputs the following:
arg 1 arg 2 arg 3
This is because "$*" considers all the positional parameters as a single word.