The difference between $@ and $* lies in how they handle quoted arguments when used in a script.
-
$@:- When used without quotes, it behaves like
$*, treating each argument as a separate word. - When used with quotes (
"$@"), it preserves each argument as a separate entity. This means that if any arguments contain spaces, they will be treated as individual arguments.
Example:
#!/bin/bash echo "Using \$@:" for arg in "$@"; do echo "$arg" doneIf you run the script with
./script.sh "arg 1" "arg 2", the output will be:Using $@: arg 1 arg 2 - When used without quotes, it behaves like
-
$*:- When used without quotes, it behaves like
$@, treating all arguments as a single word. - When used with quotes (
"$*"), it combines all arguments into a single string, with the first character of theIFS(Internal Field Separator, usually a space) used as a separator.
Example:
#!/bin/bash echo "Using \$*:" for arg in "$*"; do echo "$arg" doneIf you run the script with
./script.sh "arg 1" "arg 2", the output will be:Using $*: arg 1 arg 2 - When used without quotes, it behaves like
In summary, use "$@" when you want to preserve the individual arguments, especially if they contain spaces, and use "$*" when you want to treat all arguments as a single string.
