What is $* in Bash: Explanation and Usage
$* in Bash is a special variable that represents all the positional parameters passed to a script or function as a single word. It combines all arguments into one string separated by the first character of the IFS variable, usually a space.How It Works
Imagine you have a list of items, like groceries, and you want to mention them all in one sentence. In Bash, $* acts like that sentence, joining all the items (arguments) into one string separated by spaces or another separator defined by IFS.
When you run a script with several arguments, each argument is stored in a numbered variable like $1, $2, and so on. The $* variable collects all these arguments and presents them as one combined string. This is useful when you want to handle all inputs together instead of one by one.
Example
This example shows how $* collects all arguments into a single string.
#!/bin/bash echo "All arguments using \$* : $*" echo "Looping through arguments:" for arg in "$*"; do echo "- $arg" done
When to Use
Use $* when you want to treat all script arguments as one combined string, for example, to pass them as a single parameter to another command or to display them together.
However, if you want to preserve each argument separately, especially if they contain spaces, consider using $@ instead. $* is handy for simple cases where arguments are straightforward words.
Key Points
- $* joins all positional parameters into one string separated by the first character of
IFS. - It treats all arguments as a single word, which can cause issues if arguments contain spaces.
- Use
$*when you want a simple combined string of all arguments. - For preserving argument boundaries,
$@is usually better.
Key Takeaways
$* combines all script arguments into one string separated by spaces or IFS.$* if arguments contain spaces, as it merges them.$@.$* helps in writing flexible Bash scripts that process inputs efficiently.