bash命令扩展
以下 bash 命令替换并不像我想象的那样工作。
echo $TMUX_$(echo 1)
只打印 1 并且我期待变量 $TMUX_1
的值。我也尝试过:
echo ${TMUX_$(echo 1)}
-bash: ${TMUXPWD_$(echo 1)}: bad substitution
有什么建议吗?
The following bash command substitution does not work as I thought.
echo $TMUX_$(echo 1)
only prints 1 and I am expecting the value of the variable $TMUX_1
.I also tried:
echo ${TMUX_$(echo 1)}
-bash: ${TMUXPWD_$(echo 1)}: bad substitution
Any suggestions ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我正确理解您正在寻找的内容,那么您正在尝试以编程方式构造变量名称,然后访问该变量的值。执行此类操作通常需要一个
eval
语句:此语句的重要功能包括使用双引号,以便将
$( )
正确解释为命令替换,以及第一个$
的转义,这样它就不会在第一次被评估。实现相同目标的另一种方法是在本例中我使用两个自动连接的字符串。第一个是单引号的,因此首先不会对其进行求值。
eval
要求有一个例外:Bash 有一种间接引用方法,${!name}
,当您想要使用变量的内容作为变量时,可以使用该方法。变量名。您可以按如下方式使用它:不过,我不确定是否有一种方法可以在一个语句中执行此操作,因为您必须有一个命名变量才能使其工作。
PS 我假设
echo 1
只是一些更复杂命令的替代品;-)If I understand correctly what you're looking for, you're trying to programatically construct a variable name and then access the value of that variable. Doing this sort of thing normally requires an
eval
statement:Important features of this statement include the use of double-quotes, so that the
$( )
gets properly interpreted as a command substitution, and the escaping of the first$
so that it doesn't get evaluated the first time through. Another way to achieve the same thing iswhere in this case I used two strings which automatically get concatenated. The first is single-quoted so that it's not evaluated at first.
There is one exception to the
eval
requirement: Bash has a method of indirect referencing,${!name}
, for when you want to use the contents of a variable as a variable name. You could use this as follows:I'm not sure if there's a way to do it in one statement, though, since you have to have a named variable for this to work.
P.S. I'm assuming that
echo 1
is just a stand-in for some more complicated command ;-)您在寻找数组吗? Bash 有它们。在 bash 中创建和使用数组的方法有很多种,强烈推荐 bash 联机帮助页中有关数组的部分。下面是一个代码示例:
本例中的结果当然是两个。
以下是 bash 联机帮助页中的几行内容:
Are you looking for arrays? Bash has them. There are a number of ways to create and use arrays in bash, the section of the bash manpage on arrays is highly recommended. Here is a sample of code:
The result in this case is, of course, two.
Here are a few short lines from the bash manpage:
这有效(已测试):
但可能不是很清楚。几乎可以肯定,任何解决方案都需要在 echo 周围加上反引号才能使其正常工作。
This works (tested):
Probably not very clear though. Pretty sure any solutions will require backticks around the echo to get that to work.