我正在尝试打印Bash数组中列出的多个变量的值,如下面的最小代码示例所示。
#!/bin/bash
VAR1="/path/to/source/root"
VAR2="/path/to/target/root"
VAR3="50"
VARS=("VAR1" "VAR2" "VAR3")
for var in ${VARS[*]}; do
echo "value of $var is ${$var}"
done
这给了我一个错误
line 8: value of $var is ${$var}: bad substitution
我想要以下输出:
value of VAR1 is /path/to/source/root
value of VAR2 is /path/to/target/root
value of VAR3 is 50
我在Google和SO上搜索的效果不是很好。由于间接(即,var
遍历包含名称变量的数组,我想要值),我无法准确地说出我的搜索。但任何帮助都表示赞赏。
答案 0 :(得分:2)
使用间接引用:
#!/bin/bash
VAR1="/path/to/source/root"
VAR2="/path/to/target/root"
VAR3="50"
VARS=("VAR1" "VAR2" "VAR3")
for var in ${VARS[*]}; do
echo "value of $var is ${!var}"
done
<强>输出:强>
value of VAR1 is /path/to/source/root
value of VAR2 is /path/to/target/root
value of VAR3 is 50