Question – How to add [Y/n] confirmation in our own shell scripts? How to take input from the user as Yes/No/Y/N in bash?
Sometimes you have seen that shell scripts prompt [Y/n] or [Yes/No] to user for confirmation. This is useful to know if a user wants to proceed with the remaining steps or not. You can also add the same function to your script. This article will help you with examples of (Bash Script – Prompt to Confirm (Y/N, YES/NO)) this type of inputs.
#1. Bash (Yes/No) Prompt
This example code will prompt for confirming once if you give wrong input, the program will exit with status 1. The below example code will accept only Y or n or yes or no (Not case-sensitive).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #!/bin/bash read -r -p "Are You Sure? [Y/n] " input case $input in [yY][eE][sS]|[yY]) echo "You say Yes" ;; [nN][oO]|[nN]) echo "You say No" ;; *) echo "Invalid input..." exit 1 ;; esac |
#2 Prompt for Confirmation (in Loop)
Another example is a shell script with a while loop, that will prompt for confirmation until you give proper input like (Y, N, YES, or NO). If you give the wrong input, it will again prompt for correct input and repeat the same steps. This example will accept only Y or N or YES or NO (Not case-sensitive).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/bin/bash while true do read -r -p "Are You Sure? [Y/n] " input case $input in [yY][eE][sS]|[yY]) echo "Yes" break ;; [nN][oO]|[nN]) echo "No" break ;; *) echo "Invalid input..." ;; esac done |
Conclusion
This tutorial helped you to create a shell script, that prompts for Yes/No for user confirmation. This will help you go create a bash shell script to confirm user to continue.
4 Comments
In the 2nd example. loops goes on infinity even if user type yes or no.
use break statement to terminate the loop upon valid input.
while true
do
read -r -p “Are You Sure? [Y/n] ” input
case $input in
[yY][eE][sS]|[yY])
echo “Yes”
break
;;
[nN][oO]|[nN])
echo “No”
break
;;
*)
echo “Invalid input…”
;;
esac
done
It goes to infite loop. didn’t ask for user input !
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
test.ksh[4]: read: no query process
Thanks for your page, but there is a bug here –
This – is incorrect. You need to drop the semicolon at the end of the line ‘while true;’
while true:
do
This is correct –
while true
do
Thanks Jeff,
The article has been updated.