Software Development

How do I implement a robust Yes/No/Cancel user prompt within a Linux Bash shell script?

KI Asked by Kimberly Adams · 15-08-2024
0 upvotes 13,548 views 0 comments
The question

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

0
PA
Answered on 17-08-2024

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.

0
RI
Answered on 18-08-2024

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?

JA 19-08-2024

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?

0
SU
Answered on 20-08-2024

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.

KI 21-08-2024

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.

Share your thoughts

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

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session