How to get the n
th positional argument in Bash, where n
is variable?
Asked
Active
Viewed 4.5k times
83

Gaurang Tandon
- 6,504
- 11
- 47
- 84

hcs42
- 13,376
- 6
- 41
- 36
4 Answers
126
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
- 346,391
- 90
- 374
- 439
-
1@AlexanderOleynikov It causes a "bad substitution" error; I assume because `@` (and `*`) are "Special Parameters" and because they are not valid array names? `${@}` *does* refer to the numbered parameters, but `@` is not an array and support is not implemented to parse it as such, whereas e.g. "`${unsetvariable}`" would produce empty output because it is a valid array/variable name, just not set yet (and these exceptions are specially handled in bash's source code, I guess). I tried to find a better reason in `man bash`, but scanning for @'s made me run out of patience. ;P – Victor Zamanian Nov 30 '15 at 17:03
-
In zsh, the last option works (because why wouldn't it). – Michaël Dec 28 '21 at 13:03
13
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 Weiss
- 52,533
- 16
- 102
- 136
-
2
-
3Hi @HelloGoodbye, `$12` means `$1` and the character `2`. `${12}` means the 12th parameter. – Johannes Weiss Jul 02 '15 at 10:01
-2
Read
Handling positional parameters
and
$0: the first positional parameter
$1 ... $9: the argument list elements from 1 to 9
-
This answer does not address OP's original question. He specifically asked how to get a parameter by its index stored in a variable. – Marcel Valdez Orozco Nov 29 '16 at 01:36
-2
If you are trying to get specifically nth field or the last field in specific the simplest way is by
#!/usr/bin/sh
echo ${@:${#}}
output
sh 5.1$ sh nth_field.sh 1 23 1000 103399
103399

Hackdev17
- 29
- 5