繁体   English   中英

Bash:使用for循环读取填充数组

[英]Bash: Populate Array with read from for loop

在我的一个课程中,我被分配了一个问题集。 在其中一个练习中,我必须使用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

阵列填充正确; 你只是没有正确扩展它。

# 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM