Shell 多个数组循环输出问题

发布于 2021-11-21 23:16:32 字数 631 浏览 859 评论 5

有一段垃圾代码如下,怎么不用case的方式实现同样的功能?就是使用变量来循环输出对应的数组.

我尝试使用for i in ${arr_$flag[@]} 这种样式,可是会报错误:坏的替换.

arr_A=(1 2)
arr_B=(3 4)
arr_C=(3 4 5)

tmp="A B C"
for char in $tmp
do
    case $char in
        'A')
            for i in ${arr_A[@]}
            do
                echo $i
            done;;
        'B')
            for i in ${arr_B[@]}
            do
                echo $i
            done
            ;;
        'C')
            for i in ${arr_C[@]}
            do
                echo $i
            done
            ;;
    esac;
done

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

刘备忘录 2021-11-25 00:48:28

${!var}  这个用法很神奇,网上查了下,找到一处解释:

参数扩展的基本形式是 “${PARAMETER}”。“PARAMETER” 的值是要被替换的。当 “PARAMETER” 是一个含有多于一个数字的位置参数的时候,需要使用括号,或者当 “PARAMETER” 后接一个不会被解释成它名字一部分的字符的时候。

如果 “PARAMETER” 的第一个字符是一感叹号,Bash使用 uses the value of the variable formed from the rest of “PARAMETER” as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of “PARAMETER” itself. 这就是所谓的 indirect expansion.

原文网址:http://savs.hcc.edu.tw/~chuavv/bash/Bash-Beginners-Guide-SimplifiedChinese/ch03s04.html 

白龙吟 2021-11-24 16:48:08

${!var}  这个用法很神奇,网上查了下,找到一处解释:

参数扩展的基本形式是 “${PARAMETER}”。“PARAMETER” 的值是要被替换的。当 “PARAMETER” 是一个含有多于一个数字的位置参数的时候,需要使用括号,或者当 “PARAMETER” 后接一个不会被解释成它名字一部分的字符的时候。

如果 “PARAMETER” 的第一个字符是一感叹号,Bash使用 uses the value of the variable formed from the rest of “PARAMETER” as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of “PARAMETER” itself. 这就是所谓的 indirect expansion.

原文网址:http://savs.hcc.edu.tw/~chuavv/bash/Bash-Beginners-Guide-SimplifiedChinese/ch03s04.html 

屌丝范 2021-11-24 13:52:50

引用来自“痞子汤”的答案

arr_A=(1 2)
arr_B=(3 4)
arr_C=(3 4 5)

tmp="A B C"
for char in $tmp
do
 var="arr_"${char}"[@]"
 for i in ${!var} 
 do
    echo $i
 done
done
躲猫猫 2021-11-24 13:40:49
arr_A=(1 2)
成熟的代价 2021-11-24 10:37:09
arr_A=(1 2)
arr_B=(3 4)
arr_C=(3 4 5)

tmp="A B C"
for char in $tmp
do
 var="arr_"${char}"[@]"
 for i in ${!var} 
 do
    echo $i
 done
done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文