views:

312

answers:

6

How to get the nth positional argument in bash?

Thanks.

Edit: I forgot to say but I meant that n is a variable.

A: 
$1 $2 ... $n

$0 contains the name of the script.

Alex Barrett
+1  A: 

$n       

unwind
A: 

As you can see in the Bash by Example, you just need to use the automatic variables $1, $2, and so on.

$# is used to get the number of arguments.

Zen
A: 

Read

Handling positional parameters

and

Parameter expansion

$0: the first positional parameter

$1 ... $9: the argument list elements from 1 to 9

rahul
+3  A: 

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!

Johannes Weiß
+3  A: 

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
Dennis Williamson