BASH scripting: n-th parameter of $@ when the index is a variable?

ぐ巨炮叔叔 提交于 2021-02-18 04:47:06

问题


I want to retrieve the n-th parameter of $@ (the list of command line parameters passed to the script), where n is stored in a variable.

I tried ${$n}.

For example, I want to get the 2nd command line parameter of an invocation:

./my_script.sh alpha beta gamma

And the index should not be explicit but stored in a variable n.

Sourcecode:

n=2
echo ${$n}

I would expect the output to be "beta", but I get the error:

./my_script.sh: line 2: ${$n}: bad substitution

What am I doing wrong?


回答1:


Try this:

#!/bin/bash
args=("$@")
echo ${args[1]}

okay replace the "1" with some $n or something...




回答2:


You can use variable indirection. It is independent of arrays, and works fine in your example:

n=2
echo "${!n}"

Edit: Variable Indirection can be used in a lot of situations. If there is a variable foobar, then the following two variable expansions produce the same result:

$foobar

name=foobar
${!name}



回答3:


The following works too:

#!/bin/bash
n=2
echo ${@:$n:1}



回答4:


The portable (non-bash specific) solution is

$ set a b c d
$ n=2
$ eval echo \${$n}
b



回答5:


eval can help you access the variable indirectly, which means evaluate the expression twice.

You can do like this eval alph=\$$n; echo $alph



来源:https://stackoverflow.com/questions/10749976/bash-scripting-n-th-parameter-of-when-the-index-is-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!