How to get the nth positional argument in bash?

How to get the nth positional argument in Bash, where n is variable?


Solution 1:

Use Bash's indirection feature:

#!/bin/bash
n=3
echo ${!n}

Running that file:

$ ./ind apple banana cantaloupe dates

Produces:

cantaloupe

Edit:

You can also do array slicing:

echo ${@:$n:1}

but not array subscripts:

echo ${@[n]}  #  WON'T WORK

Solution 2:

If N is saved in a variable, use

eval echo \${$N}

if it's a constant use

echo ${12}

since

echo $12

does not mean the same!