How do I prompt for Yes/No/Cancel input in a Linux shell script?

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:

  1. Loop Until Valid Input:
    The while true loop ensures the script reprompts until a valid answer is given.
  2. Read Input:
    read -r -p "..." response captures user input.
  • -r prevents backslash interpretation.
  • -p displays the prompt message.
  1. Case-Insensitive Check:
    case "${response,,}" converts the input to lowercase for simplified matching.
  2. Handle Cases:
  • Yes (y|yes): Breaks the loop and continues the script.
  • No (n|no): Exits with status 0 (successful abort).
  • Cancel (c|cancel): Exits with status 1 (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, or cancel (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.

Leave a Reply

Your email address will not be published. Required fields are marked *