问题描述
说我有两个变量;
var_one_string=foo
var_two_string=bar
我将如何完成类似的工作(伪代码示例);
How would I accomplish something like this (pseudo code examples);
示例1
for i in one two; do
echo $var_${i}_string
done
# Desired output
foo
bar
示例2
for i in one two; do
echo $var_$(echo ${i})_string
done
# Desired output
foo
bar
我知道这是错误的替换,我只是想知道是否有一种方法可以将字符串嵌套在另一个变量调用中?
I understand that this is bad substitution, I am just wondering if there is a way to nest a string within another variable call?
我能够使它正常工作
var_one_string=foo
var_two_string=bar
for i in $(echo ${!var_*}); do
echo ${!i}
done
foo
bar
推荐答案
使用内置的 declare
以及 bash
中的间接变量扩展.首先,将数组中具有动态性质的元素定义为
Use the declare
built-in along with indirect-variable expansion in bash
. First define the elements of for the dynamic nature in an array as
#!/bin/bash
list=(one two)
unset count
for var in "${list[@]}"; do
declare var_${var}_string="string"$((++count))
done
现在使用间接扩展访问创建的变量
and now access the created variables using indirect expansion
for var in "${list[@]}"; do
dymv="var_${var}_string"
echo "${!dymv}"
done
,切勿为此要求使用 eval
.由于使用有害命令不太可能注入代码,因此可能很危险.
and never use eval
for this requirement. Could be dangerous because of unlikely code-injection possibility with a harmful command.
这篇关于在bash中,是否有一种方法可以在变量中替代或嵌套变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!