I am building a deployment automation tool and need to add a confirmation step before critical actions are executed. How can I create a clean prompt that accepts 'Yes', 'No', or 'Cancel' (Y/N/C) inputs from the user? I'm looking for a solution that handles both uppercase and lowercase inputs gracefully and ensures the script exits or loops correctly if the user provides an invalid response.
3 answers
The most idiomatic and readable way to handle multi-option prompts in Bash is using the read command combined with a case statement. Using read -p allows you to display the prompt message on the same line as the input. To ensure robustness, you should wrap the logic in a while loop so that the script repeatedly asks for input if the user enters something unrecognizable. For the "Cancel" option, you can either call exit to stop the entire process or return if the prompt is inside a function. This approach is highly portable across different Linux distributions and requires no external dependencies.
Are you looking for a simple text-based prompt, or would you be interested in using something like zenity or whiptail to create a more visual, TUI-based (Terminal User Interface) dialog box for your script?
To handle a default, you can set the variable before the read command or use [ -z "$input" ] to catch the empty string and assign it to 'Yes' or your preferred default choice.
I agree with Susan. A common trick is to display the default in uppercase, like [Y/n/c]. In your case statement, just add an empty pattern "" ) right before your 'Yes' logic to catch the Enter key.
Since this script will be running on remote servers via SSH, I prefer to keep it strictly text-based. I've seen whiptail used before, but I'm worried about it not being installed on minimal server environments. A standard Bash case statement seems safer for compatibility. How would I handle a default value if the user just hits the 'Enter' key without typing anything?