How can you access each argument inside the script?

QuestionsQuestions8 SkillsProDec, 13 2025
0135

That's an excellent and crucial question for understanding Bash scripting!

In Bash, arguments passed to a script are stored in special variables:

  • $1: Represents the first argument.
  • $2: Represents the second argument.
  • $3: Represents the third argument.
  • ...and so on, using $n for the nth argument.

You can see this in action directly in the script you're working with. For instance:

  • In the elif [ $# -eq 1 ] block, it uses echo "One argument provided: $1" to display the first argument.
  • In the elif [ $# -eq 2 ] block, it uses echo "Two arguments provided: $1 and $2" to display both the first and second arguments.
  • In the else block (for more than two arguments), it explicitly prints $1, $2, and $3.

So, to access any specific argument, you simply refer to it by its position using $1, $2, $3, etc.

Do you want to try modifying the script to display, say, the fourth argument if it exists?

0 Comments

no data
Be the first to share your comment!