2016-10-11 65 views
1

在我的一個類中,我已經分配了一個問題集。在其中一個練習中,我必須使用for循環和read命令來接收三個字符串,然後在我的數組中使用(...)中的select選項。下面是我的代碼,但我似乎無法使用for循環正確地填充數組。我已經想出了幾個選擇,但我必須使用這個一般結構。Bash:使用從循環讀取的數組填充

echo Please type in 3 foods you like: 
for xx in `seq 1 3`; do 
    read -p "enter food $xx " array[$xx] 
    echo $array 
done 

PS3='Now Select the food you like the best: ' 
select option in array 
do 
    echo "The option you have selected is: $option" 
    break 
done 

回答

3

該數組填充正確;你只是不是擴大它正確。

# Don't use seq; just use bash's C-style for loop. 
# The only reason to avoid this kind of loop is 
# to make your shell script POSIX-compatible, but 
# seq isn't part of the POSIX standard either. 
    for ((xx=1; xx<=3; xx++)); do # Don't use seq 
    read -p "Enter foo $xx" array[xx] 
    echo "${array[@]}" 
done 

PS3='Now Select the food you like the best: ' 
select option in "${array[@]}" 
do 
    echo "The option you have selected is: $option" 
    break 
done 
+0

非常感謝。我已經設法弄清楚了閱讀內容,但是我仍然停留在回聲部分。謝謝! – Dent7777