How to get the nth positional argument in bash?

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

+66
bash arguments command-line-arguments
Sep 30 '09 at 12:29
source share
5 answers

Use Bash Binding Function:

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

Running this file:

 $ ./ind apple banana cantaloupe dates 

It produces:

 cantaloupe 

Edit:

You can also slice an array:

 echo ${@:$n:1} 

but not array indices:

 echo ${@[n]} # WON'T WORK 
+92
Sep 30 '09 at 15:26
source share

If N stored in a variable, use

 eval echo \${$N} 

if it is permanent use

 echo ${12} 

So

 echo $12 

doesn't mean the same thing!

+10
Sep 30 '09 at 12:34
source share
 $1 $2 ... $n 

$0 contains the name of the script.

+6
Sep 30 '09 at 12:31
source share

As you can see in Bash with an example , you just need to use automatic variables $ 1, $ 2, etc.

$ # is used to get the number of arguments.

0
Sep 30 '09 at 12:31
source share

Read

Positional Parameter Processing

and

Parameter Extension

$ 0: first positional parameter

$ 1 ... $ 9: items in the argument list from 1 to 9

-one
Sep 30 '09 at 12:33
source share



All Articles