How to get the nth positional argument in bash?

BashArgumentsCommand Line-Arguments

Bash Problem Overview


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

Bash Solutions


Solution 1 - Bash

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 - Bash

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!

Solution 3 - Bash

Read

Handling positional parameters

and

Parameter expansion

$0: the first positional parameter

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhcs42View Question on Stackoverflow
Solution 1 - BashDennis WilliamsonView Answer on Stackoverflow
Solution 2 - BashJohannes WeissView Answer on Stackoverflow
Solution 3 - BashrahulView Answer on Stackoverflow