How to pass multiple arguments?

QuestionsQuestions8 SkillsProDec, 22 2025
0113

Passing multiple arguments is very simple! You just separate them with spaces when you run your script in the terminal.

1. How to Run the Script with Multiple Arguments

In your terminal, you would type:

./arguments.sh value1 value2 value3

2. How to Access Them Inside Your Script

Bash automatically assigns each argument to a numbered variable based on its position:

  • $1: The first argument (value1)
  • $2: The second argument (value2)
  • $3: The third argument (value3)
  • ... and so on up to $9. (For 10 or more, you use ${10}).

3. A Practical Example

Try updating your arguments.sh file with this code:

#!/bin/bash

echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"

Then, run it in the terminal like this:

bash arguments.sh Red Green Blue

The output will be:

First argument: Red
Second argument: Green
Third argument: Blue

Useful Special Variables for Multiple Arguments:

As you progress in this lab, you'll find these very helpful:

  • $#: Tells you the total number of arguments passed (in the example above, it would be 3).
  • $@: Represents all the arguments passed to the script at once.

Important Note: If an argument contains a space (like New York), you must wrap it in quotes: ./arguments.sh "New York" London. In this case, $1 would be New York.

0 Comments

no data
Be the first to share your comment!