在 BASH 脚本中使用字符串作为变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8435256/
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
Use string as variable name in BASH script
提问by Andy
I have the following:
我有以下几点:
#!/bin/sh
n=('fred' 'bob')
f='n'
echo ${${f}[@]}
and I need that bottom line after substitutions to execute
我需要在替换后执行该底线
echo ${n[@]}
any way to do this? I just get
有什么办法可以做到这一点?我只是得到
test.sh: line 8: ${${f}}: bad substitution
on my end.
在我这边。
回答by Michael Hoffman
You can do variable indirection with arrays like this:
您可以使用这样的数组进行变量间接访问:
subst="$f[@]"
echo "${!subst}"
As soulmerge notes, you shouldn't use #!/bin/shfor this. I use #!/usr/bin/env bashas my shebang, which should work regardless of where Bash is in your path.
正如灵魂合并所指出的那样,您不应该#!/bin/sh为此使用。我#!/usr/bin/env bash用作我的shebang,无论Bash 在您的路径中的哪个位置,它都应该起作用。
回答by soulmerge
You could evalthe required line:
您可以eval使用所需的行:
eval "echo ${${f}[@]}"
BTW: Your first line should be #!/bin/bash, you're using bash-specific stuff like arrays
顺便说一句:你的第一行应该是#!/bin/bash,你使用的是 bash 特定的东西,比如数组

