How does the special variable $@ differ from $* in a bash script?

0224

In a bash script, $@ and $* are both special variables that represent all the positional parameters (arguments) passed to the script, but they handle quoting differently.

  • $@: When used in double quotes ("$@"), it treats each argument as a separate quoted string. This means that if any argument contains spaces, it will be preserved as a single argument.

  • $*: When used in double quotes ("$*") it treats all arguments as a single string, with each argument separated by the first character of the IFS (Internal Field Separator), which is a space by default.

Example:

#!/bin/bash

echo "Using \$@:"
for arg in "$@"; do
    echo "$arg"
done

echo "Using \$*:"
for arg in "$*"; do
    echo "$arg"
done

If you run the script with the following command:

./script.sh "arg 1" "arg 2" "arg 3"

The output will be:

Using $@:
arg 1
arg 2
arg 3

Using $*:
arg 1 arg 2 arg 3

In summary, use "$@" when you want to preserve the individual arguments, and use "$*" when you want to treat all arguments as a single string.

0 Comments

no data
Be the first to share your comment!