That's an excellent question! Using $@ without quotes is one of the most common pitfalls in Bash scripting.
When you use $@ (without quotes) instead of "$@" (with quotes), Bash performs something called Word Splitting.
The Problem: Handling Spaces
If an argument contains a space, Bash will "break" that single argument into multiple pieces.
Imagine you have this script:
for arg in $@; do # No quotes!
echo "Argument: $arg"
done
If you run it like this:
./arguments.sh "Hello World"
- With quotes (
"$@"): It seesHello Worldas one item.- Output:
Argument: Hello World
- Output:
- Without quotes (
$@): Bash splits it at the space and thinks you passed two items.- Output:
Argument: Hello Argument: World
- Output:
Summary of the difference:
| Feature | "$@" (Quoted) |
$@ (Unquoted) |
|---|---|---|
| Integrity | Preserves arguments exactly as they were typed. | Splits arguments if they contain spaces. |
| Standard | Almost always the preferred way. | Rare; only used if you want Bash to split words. |
Labby's Tip: Always wrap your variables in quotes (like "$@") to ensure your script handles user input safely!