How to access all arguments?

0108

In a Bash script, you can access all the arguments passed to the script using the special variable $@ or $*. Here's how they work:

  • $@: Represents all the arguments as separate quoted strings. This is useful when you want to iterate over each argument individually.
  • $*: Represents all the arguments as a single string. This is useful when you want to treat all arguments as one.

Example Script:

Here's a simple script that demonstrates how to access all arguments:

#!/bin/bash

echo "All arguments using \$@:"
for arg in "$@"; do
    echo "$arg"
done

echo "All arguments using \$*:"
echo "$*"

Explanation:

  • The for loop iterates over each argument when using $@, printing them one by one.
  • When using $*, it prints all arguments as a single line.

Example Usage:

If you run the script with:

bash example.sh arg1 arg2 arg3

The output will be:

All arguments using $@:
arg1
arg2
arg3
All arguments using $*:
arg1 arg2 arg3

Let me know if you need more information!

0 Comments

no data
Be the first to share your comment!