从Bash数组中列出的变量名称中获取变量值 [英] Getting variable values from variable names listed in array in Bash
本文介绍了从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
这篇关于从Bash数组中列出的变量名称中获取变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文