Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the nth positional argument in bash?

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

like image 283
hcs42 Avatar asked Sep 30 '09 12:09

hcs42


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does $# do in bash?

$# is a special variable in bash , that expands to the number of arguments (positional parameters) i.e. $1, $2 ... passed to the script in question or the shell in case of argument directly passed to the shell e.g. in bash -c '...' .... . This is similar to argc in C.

What is a positional argument in bash?

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0 . Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command.

What is N in bash?

-n is one of the string operators for evaluating the expressions in Bash. It tests the string next to it and evaluates it as "True" if string is non empty. Positional parameters are a series of special variables ( $0 , $1 through $9 ) that contain the contents of the command line argument to the program.


2 Answers

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 
like image 106
Dennis Williamson Avatar answered Sep 29 '22 16:09

Dennis Williamson


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!

like image 44
Johannes Weiss Avatar answered Sep 29 '22 17:09

Johannes Weiss