To prompt for Yes/No/Cancel input in a Linux shell script, you can use a loop with the read
command and a case
statement to handle user input. Here’s a concise and robust implementation:
#!/bin/bash
while true; do
read -r -p "Proceed? [Y]es/[N]o/[C]ancel: " response
case "${response,,}" in # Convert response to lowercase
y|yes)
echo "Proceeding..."
break
;;
n|no)
echo "Aborting..."
exit 0
;;
c|cancel)
echo "Cancelled by user."
exit 1
;;
*)
echo "Invalid option. Please enter Y, N, or C."
;;
esac
done
# Continue script execution if "Yes" is chosen
Explanation:
- Loop Until Valid Input:
Thewhile true
loop ensures the script reprompts until a valid answer is given. - Read Input:
read -r -p "..." response
captures user input.
-r
prevents backslash interpretation.-p
displays the prompt message.
- Case-Insensitive Check:
case "${response,,}"
converts the input to lowercase for simplified matching. - Handle Cases:
- Yes (
y|yes
): Breaks the loop and continues the script. - No (
n|no
): Exits with status0
(successful abort). - Cancel (
c|cancel
): Exits with status1
(error/cancellation). - Invalid Input: Displays an error and reprompts.
Example Usage:
$ ./script.sh
Proceed? [Y]es/[N]o/[C]ancel: maybe
Invalid option. Please enter Y, N, or C.
Proceed? [Y]es/[N]o/[C]ancel: Y
Proceeding...
Key Features:
- Flexible Input: Accepts
y
,yes
,n
,no
,c
, orcancel
(case-insensitive). - Clear Exits:
exit 0
for “No” (graceful termination).exit 1
for “Cancel” (explicit cancellation).- Validation: Rejects all invalid inputs until a valid choice is made.