Reputation: 13
I am requesting user input using read. I would like to match the input to an array, and if it matches, print the next item in the array.
For example:
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
I would only like to print the very next day. (So if the user inputs 'Wednesday' I would like only 'Thursday' to be returned. With the script above only the day 'Monday' is returned.
Upvotes: 1
Views: 71
Reputation: 8972
Just loop over the array by index until you find the day and increase the index again after the loop.
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]}
Upvotes: 1
Reputation: 399
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
Upvotes: 0