从Bash数组中列出的变量名称中获取变量值
问题描述:
我正在尝试打印Bash数组中列出的多个变量的值,如下面的最小代码示例所示.
I'm trying to print values of multiple variables that are listed in a Bash array as evident in the minimal code example below.
#!/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
遍历包含我想要其 values 的变量的 names 的数组),我无法准确说出我的搜索字词.但我们会提供任何帮助.
My search on Google and SO was not very fruitful. Because of the indirection (i.e., var
iterates over an array containing names of variables for which I want the values), I'm not able to precisely word my search. But any help is appreciated.
答
使用间接引用为:
#!/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