在我的一个课程中,我被分配了一个问题集。在其中一个练习中,我必须使用for循环和read命令接受三个字符串,然后在我的数组中使用(...)中的select选项。下面是我的代码,但我似乎无法使用for循环正确填充数组。我已经找到了一些替代方案,但我必须使用这种一般结构。
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
答案 0 :(得分: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