How to get the nth positional argument in bash?

hcs42 picture hcs42 · Sep 30, 2009 · Viewed 34.4k times · Source

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

Answer

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