How to get the nth positional argument in bash?

2019-01-21 04:26发布

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

5条回答
Rolldiameter
2楼-- · 2019-01-21 05:02

As you can see in the Bash by Example, you just need to use the automatic variables $1, $2, and so on.

$# is used to get the number of arguments.

查看更多
我只想做你的唯一
3楼-- · 2019-01-21 05:06

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
查看更多
地球回转人心会变
4楼-- · 2019-01-21 05:12
$1 $2 ... $n

$0 contains the name of the script.

查看更多
smile是对你的礼貌
5楼-- · 2019-01-21 05:17

Read

Handling positional parameters

and

Parameter expansion

$0: the first positional parameter

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

查看更多
Root(大扎)
6楼-- · 2019-01-21 05:20

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!

查看更多
登录 后发表回答