根据用户输入返回数组中的下一项
Returning the next item in an array based on user input
我正在使用读取请求用户输入。我想将输入与数组匹配,如果匹配,则打印数组中的下一项。
例如:
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
我只想在第二天打印。 (因此,如果用户输入 'Wednesday',我只想返回 'Thursday'。使用上面的脚本,仅返回 'Monday' 日。
只需按索引遍历数组,直到找到日期并在循环后再次增加索引。
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]}
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
我正在使用读取请求用户输入。我想将输入与数组匹配,如果匹配,则打印数组中的下一项。
例如:
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
我只想在第二天打印。 (因此,如果用户输入 'Wednesday',我只想返回 'Thursday'。使用上面的脚本,仅返回 'Monday' 日。
只需按索引遍历数组,直到找到日期并在循环后再次增加索引。
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]}
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