bash:循环嵌套循环中的变量

时间:2018-09-17 05:19:06

标签: bash

    s1="
    production_1
    produciont_2
    production_3
    "
    production_1="
    a.jar
    b.jar
    "
    production_2="
    c.jar
    d.jar
    "

    production_3="
    e.jar
    f.jar
    "

    for i in `eval \$$s1`
    do
       echo $i
    done

$ bash 1.sh
1.sh: line 23: 27782s1: command not found

如何在上述嵌套循环中打印变量? 谢谢。

预期结果: a.jar b.jar c.jar d.jar e.jar f.jar

1 个答案:

答案 0 :(得分:1)

我的解决方案:

#!/bin/bash

print_array_by_name () {
    declare -a _array1=("${!1}")
    echo "${_array1[@]}" 
}

s1="production_1
production_2
production_3"

production_1="a.jar
b.jar"

production_2="c.jar
d.jar"

production_3="e.jar
f.jar"

for i in ${s1[@]}
do
   print_array_by_name "$i[@]"
done

输出:

$ ./script.sh
a.jar
b.jar
c.jar
d.jar
e.jar
f.jar