Skip to main content
When writing Bash scripts, handling command-line arguments efficiently is crucial. You can access each argument by its position ($1, $2, …), but when the number of parameters varies, special variables like $@ and $* simplify your logic. This guide covers:
  • Positional parameters
  • Grouping arguments
  • Iterating with "$@" vs "$*"
  • The impact of quoting
  • Customizing the internal field separator (IFS)
  • Compatibility considerations

1. Positional Parameters: $1, $2, …

By default, Bash assigns each argument to a numbered variable:
When you need to accept an unpredictable number of parameters, indexing each one becomes cumbersome. That’s where $@ and $* come in.

2. Grouping All Arguments: $@ vs $*

Both $@ and $* collect all positional arguments:
The image illustrates the special shell variables $* and $@, accompanied by a graphic of twelve cylindrical objects arranged in a grid.
Both variables contain the full list of parameters, but they differ when you iterate over them.

3. Iterating with a For Loop

Compare two scripts that loop over their arguments:
The image illustrates the concept of special shell variables $* and $@, using a visual representation of containers and arrows.
In the soda‐can analogy:
  • $@ places each can in its own compartment.
  • $* pours all the soda into one big bottle—individual cans are no longer separate.
The image illustrates the difference between special shell variables $@ and $*, using a visual representation of containers to show how they handle arguments.

4. The Importance of Double Quotes

Always quote $@ and $*:
  • "$@" expands each argument separately.
  • "$*" joins all arguments into a single string, separated by the first character of IFS (default: space).
Unquoted, both behave identically:

5. Modifying the Internal Field Separator (IFS)

You can change IFS to alter how "$*" joins arguments:
Splitting later requires unquoted iteration:

6. Compatibility with Older Bash Versions

Some pre-4.0 Bash releases split unquoted assignments differently. For example, under Bash 3:
Still, quoting on assignment ensures consistent splitting:

7. Summary: $@ vs $*


8. Conclusion

  • Use "$@" when you need to preserve each argument.
  • Use "$*" to aggregate them into a single string with a custom delimiter.
  • Always quote both to maintain consistent behavior across Bash versions and avoid word-splitting pitfalls.
The image shows a comparison between special shell variables $@ and $*, with a recommendation to surround them with double quotes.

Watch Video