2013-03-06 75 views
0

我試圖聲明,賦值和調用變量在循環內運行用戶定義的時間量。我希望這些變量在循環後可用。我所試圖做的是:Bash:聲明,賦值給一個變量並在一個循環內調用它

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環路)四個變量將被創建和分配的用戶輸入值。我打算稍後使用這些變量。

非常感謝您的幫助!

回答

0

你可以使用一個數組(可能是首選的方法),或者你可以做一些eval體操。 bash手冊頁提供了你需要知道的一切。

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循環之後,只要你不做任何事情,使在子shell中for循環運行(如把它放在一個管道或將其包含在(...)等)

+0

謝謝你這麼多解釋這一點,兩者都很好,我學到了新的東西! – Nikl 2013-03-07 09:13:51

+0

我有一個額外的問題,這段代碼工作得很好,如果我獨立運行它,但是一旦我將它嵌入到腳本中,它將返回一個¨read:cold [r]:錯誤的變量名稱,一旦它到達讀取部分,仍然在循環中。它不會在任何子shell或管道中運行,用括號括起來。你是否知道問題可能是什麼? – Nikl 2013-03-07 12:26:58

+0

:那是當我運行陣列解決方案。 – Nikl 2013-03-07 12:30:54