BASH 脚本:当索引是变量时 $@ 的第 n 个参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10749976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:22:53  来源:igfitidea点击:

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

bashshellargv

提问by nosid

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.

我想检索 $@ 的第 n 个参数(传递给脚本的命令行参数列表),其中 n 存储在一个变量中。

I tried ${$n}.

我试过 ${$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.

并且索引不应该是显式的,而是存储在变量 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?

我究竟做错了什么?

采纳答案by konqi

Try this:

尝试这个:

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

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

好的,用一些 $n 或其他东西替换“1”...

回答by nosid

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

您可以使用变量间接。它独立于数组,在您的示例中工作正常:

n=2
echo "${!n}"

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

编辑:变量间接可以在很多情况下使用。如果存在变量foobar,则以下两个变量扩展会产生相同的结果:

$foobar

name=foobar
${!name}

回答by Smi

The following works too:

以下也有效:

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

回答by Jens

The portable (non-bash specific) solution is

便携式(非 bash 特定)解决方案是

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

回答by Summer_More_More_Tea

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

eval可以帮助您间接访问变量,这意味着对表达式求值两次。

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

你可以这样做 eval alph=\$$n; echo $alph