83

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

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
hcs42
  • 13,376
  • 6
  • 41
  • 36

4 Answers4

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

Read

Handling positional parameters

and

Parameter expansion

$0: the first positional parameter

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

Community
  • 1
  • 1
rahul
  • 184,426
  • 49
  • 232
  • 263
-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