Bash:声明,为变量赋值并在循环内调用它

时间:2013-03-06 16:21:09

标签: bash variables for-loop ubuntu-12.04

我正在尝试声明,在一个运行用户定义的次数的循环中分配值和调用变量。我希望循环后这些变量可用。我想做的是:

echo "HOW MANY ROUNDS OF TEST ITERATIONS WOULD YOU LIKE TO RUN?"
read round_nr
echo "Number of Iteration rounds set to: $round_nr!"

for r in $(seq 1 $round_nr); do
    echo "HOW MANY COLD TEST ITERATIONS DO YOU WANT IN ROUND $r?"
    read COLD$r
    echo "HOW MANY WARM TEST ITERATIONS DO YOU WANT IN ROUND $r?"
    read WARM$r
    echo "HOW MANY HOT TEST ITERATIONS DO YOU WANT IN ROUND $r?"
    read HOT$r
    echo "HOW MANY NR OF FIXES PER TEST ITERATION $r?"
    read NUMFIX$r
    echo "ITERATION $r INPUT VALUES: COLD/WARM/HOT/NUMFIX:"
    echo $COLD$r $WARM$r $HOT$r $NUMFIX$r
done  

以这种方式,对于每个循环(在用户定义的round_nr循环集合中),将创建四个变量并分配用户输入值。我打算稍后使用这些变量。

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您确实可以使用declare,但使用数组会容易得多。 (我使用-p read标志来节省空间;您不需要使用它。)

for r in $(seq 1 $round_nr); do
    read -p "HOW MANY COLD TEST ITERATIONS DO YOU WANT IN ROUND $r?" ans
    declare "COLD$r=$ans"
    read -p "HOW MANY WARM TEST ITERATIONS DO YOU WANT IN ROUND $r?" ans
    declare "WARM$r=$ans"
    read -p "HOW MANY HOT TEST ITERATIONS DO YOU WANT IN ROUND $r?" ans
    declare "HOT$r=$ans"
    read -p "HOW MANY NR OF FIXES PER TEST ITERATION $r?" ans
    declare "NUMFIX$r=$ans"
    echo "ITERATION $r INPUT VALUES: COLD/WARM/HOT/NUMFIX:"

    # Here's the tricky part. It's easier to create the variable than it
    # is to use it.
    varcold="COLD$r"
    varwarm="WARM$r"
    varhot="HOT$r"
    varnumfix="COLD$r"

    echo ${!varcold} ${!varwarm} ${!varhot} ${!varnumfix}
done  

使用数组,它只是

for r in $(seq 1 $round_nr); do
    read -p "HOW MANY COLD TEST ITERATIONS DO YOU WANT IN ROUND $r?" cold[r]
    read -p "HOW MANY WARM TEST ITERATIONS DO YOU WANT IN ROUND $r?" warm[r]
    read -p "HOW MANY HOT TEST ITERATIONS DO YOU WANT IN ROUND $r?" hot[r]
    read -p "HOW MANY NR OF FIXES PER TEST ITERATION $r?" numfix[r]
    echo "ITERATION $r INPUT VALUES: COLD/WARM/HOT/NUMFIX:"
    echo ${cold[r]} ${warm[r]} ${hot[r]} ${numfix[r]}
done

在任何一种情况下,变量都将在for循环之后全部可用,只要你不做任何事情来使for循环在子shell中运行(比如把它放在一个子shell中)管道或将其封装在(...)等)

答案 1 :(得分:0)

你可以使用数组(可能是首选方法),或者你可以做一些eval体操。 bash手册页包含您需要知道的所有内容。