What is the difference between $@ and $*?

0193

The difference between $@ and $* lies in how they handle quoted arguments when used in a script.

  1. $@:

    • 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"
    done

    If you run the script with ./script.sh "arg 1" "arg 2", the output will be:

    Using $@:
    arg 1
    arg 2
  2. $*:

    • 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 the IFS (Internal Field Separator, usually a space) used as a separator.

    Example:

    #!/bin/bash
    echo "Using \$*:"
    for arg in "$*"; do
        echo "$arg"
    done

    If you run the script with ./script.sh "arg 1" "arg 2", the output will be:

    Using $*:
    arg 1 arg 2

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.

0 Comments

no data
Be the first to share your comment!