What is the difference between $@ and $* in shell scripts?

ShellScripting

Shell Problem Overview


In shell scripts, what is the difference between $@ and $*?

Which one is the preferred way to get the script arguments?

Are there differences between the different shell interpreters about this?

Shell Solutions


Solution 1 - Shell

From here:

> $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them.

Take this script for example (taken from the linked answer):

for var in "$@"
do
    echo "$var"
done

Gives this:

$ sh test.sh 1 2 '3 4'
1
2
3 4

Now change "$@" to $*:

for var in $*
do
    echo "$var"
done

And you get this:

$ sh test.sh 1 2 '3 4'
1
2
3
4

(Answer found by using Google)

Solution 2 - Shell

A key difference from my POV is that "$@" preserves the original number of arguments. It's the only form that does. For that reason it is very handy for passing args around with the script.

For example, if file my_script contains:

#!/bin/bash

main()
{
   echo 'MAIN sees ' $# ' args'
}

main $*
main $@

main "$*"
main "$@"

### end ###

and I run it like this:

my_script 'a b c' d e

I will get this output:

MAIN sees 5 args

MAIN sees 5 args

MAIN sees 1 args

MAIN sees 3 args

Solution 3 - Shell

With $@ each parameter is a quoted string. Otherwise it behaves the same.

See: http://tldp.org/LDP/abs/html/internalvariables.html#APPREF

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnicoulajView Question on Stackoverflow
Solution 1 - ShellMark ByersView Answer on Stackoverflow
Solution 2 - ShellArt SwriView Answer on Stackoverflow
Solution 3 - ShellGavin HView Answer on Stackoverflow