让bash遍历未知数量的变量 [英] Let bash loop over unknown number of variables
本文介绍了让bash遍历未知数量的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件,其中定义了一堆变量.可能是一,四或二十.它们具有诸如 ipt_rss
和 bhd_rss
之类的名称.我们将这些变量称为 var_i
I have a file where a bunch of variables are defined. It could be one, four or twenty. They have names such as ipt_rss
and bhd_rss
. Let's call these variables var_i
现在,我想让bash像这样循环遍历这些变量:
Now, I'd like to let bash loop over these variables like this:
for all i in var_i do
command1 arg command2 arg $var_1 > /some/directory/$var_i.rss
echo "Success finding $var_i"
done
我该怎么做?
推荐答案
如果变量开始都带有通用前缀,则可以遍历所有此类变量名称,并对结果使用间接变量扩展:
If the variables all begin with a common prefix, you can iterate over all such variable names and use indirect variable expansion on the results:
for var in ${!rss_*}; do # rss_ipt, rss_bhd, etc
command1 arg command2 arg "${!var}" > "/some/directory/${!var}.rss"
done
否则,您能做的最好的事情就是显式定义一个变量名称数组,或对名称列表进行硬编码:
Otherwise, the best you can do is explicitly define an array of variable names, or hard-code the list of names:
vars=( ipt_rss bhd_rss ... )
for var in "${vars[@]}"; do
或
for var in ipt_rss bhd_rss; do
这篇关于让bash遍历未知数量的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文