0

我试图在运行用户定义次数的循环内声明、赋值和调用变量。我希望这些变量在循环后可用。我想做的是:

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 循环中),将创建四个变量并分配用户输入值。我计划稍后使用这些变量。

非常感谢您的帮助!

4

2 回答 2

2

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

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中运行(例如将其放入管道中或将其包含在 中(...),等等),变量都将在循环之后可用

于 2013-03-06T16:44:00.503 回答
0

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

于 2013-03-06T16:24:35.590 回答