How to get the n
th positional argument in Bash, where n
is variable?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
回答2:
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!
回答3:
$1 $2 ... $n
$0
contains the name of the script.
回答4:
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.
回答5:
Read
Handling positional parameters
and
Parameter expansion
$0: the first positional parameter
$1 ... $9: the argument list elements from 1 to 9