根据用户输入返回数组中的下一个项目

时间:2015-09-07 13:03:06

标签: arrays bash variables iteration user-input

我正在使用read请求用户输入。我想将输入与数组匹配,如果匹配,则打印数组中的下一项。

例如:

echo "What day of the week is it?"
read day
for d in "$(week[@])" do
if [ "$d" == "$day" ]; then
echo "The next day of the week is ${week [d++]}."
fi
done

我只想在第二天打印。 (因此,如果用户输入'星期三',我希望只返回'星期四'。使用上面的脚本只返回'星期一'那天。

2 个答案:

答案 0 :(得分:1)

按索引循环遍历数组,直到找到日期并在循环后再次增加索引。

week=(Su Mo Tu We Th Fr Sa Su)  # another Su at the end
read day

i=0
until [[ ${week[i]} == $day ]]; do
    let i++
done

echo ${week[++i]}

答案 1 :(得分:0)

week=(Sun Mon Tue Wed Thu Fri Sat)

i=0
for str in ${week[@]}; do
  if [[ $str = "$day" ]]; then
         i=$(((i+1)%7))                #Get index 0 if day is saturday
         echo "Next day is ${week[i]}" 
        break 
    fi
     i=$((i+1)) 
done