How can you access the nth argument passed to a shell script?

QuestionsQuestions8 SkillsProDec, 20 2025
0112

Great question! You’ve already seen how to use $1 and $2. To access the nth argument, you generally follow the same pattern, but there is one important rule to remember for numbers higher than 9.

1. Arguments 1 through 9

For the first nine arguments, you can access them directly using a single digit:

  • $1, $2, $3, ... $9

2. Arguments 10 and beyond (The Curly Brace Rule)

If you want to access the 10th argument or higher (the "nth" argument where n > 9), you must wrap the number in curly braces {}.

  • Correct: ${10}, ${11}, ${n}
  • Incorrect: $10 (The shell would interpret this as $1 followed by a literal "0")

Example:

If you have a script and you run it like this:

./my_script.sh a b c d e f g h i j

To print the 10th argument (j), your script would need:

echo "The 10th argument is ${10}"
  • $n or ${n}: Accesses a specific argument by its position.
  • $#: Tells you the total number of arguments passed (useful if you don't know what "n" is beforehand).
  • $@: Accesses all arguments at once.

Writing ${n} is actually a good habit to get into even for small numbers (like ${1}), as it makes the variable name very explicit to the Shell!

0 Comments

no data
Be the first to share your comment!