Do your input in a loop. Exit the loop with break
(or exit
as the case may be) if you get a valid response from the user.
while true; do
read -p 'Continue? yes/no: ' input
case $input in
[yY]*)
echo 'Continuing'
break
;;
[nN]*)
echo 'Ok, exiting'
exit 1
;;
*)
echo 'Invalid input' >&2
esac
done
As a utility function:
ask_continue () {
while true; do
read -p 'Continue? yes/no: ' input
case $input in
[yY]*)
echo 'Continuing'
break
;;
[nN]*)
echo 'Ok, exiting'
exit 1
;;
*)
echo 'Invalid input' >&2
esac
done
}
A variation of the utility function that allows exiting through EOF (e.g. pressing Ctrl+D):
ask_continue () {
while read -p 'Continue? yes/no: ' input; do
case $input in
[yY]*)
echo 'Continuing'
return
;;
[nN]*)
break
;;
*)
echo 'Invalid input' >&2
esac
done
echo 'Ok, exiting'
exit 1
}
Here, there are three ways out of the loop:
- The user enters "yes", in which case the function returns.
- The user enters "no", in which case the we
break
out of the loop and execute exit 1
.
- The
read
fails due to something like encountering an end-of-input or some other error, in which case the exit 1
is executed.
Instead of exit 1
you may want to use return 1
to allow tho caller to decide what to do when the user does not want to continue. The calling code may then look like
if ! ask_continue; then
# some cleanup, then exit
fi
Y and N
, am i right? – Siva Sep 03 '18 at 16:30select
statement - that one doesn't exit until you have valid input, IIRC – Sergiy Kolodyazhnyy Sep 03 '18 at 18:47