How do I prompt for Yes/No/Cancel input in a Linux shell script?
You can prompt for Yes, No, or Cancel in a Bash script by:
- Displaying a prompt (e.g., “y/n/c”)
- Reading a single character of user input
- Using a
case
statement to handle each response appropriately
Here’s a simple example:
#!/usr/bin/env bash echo "Do you wish to continue?" echo "(y)es, (n)o, or (c)ancel:" read -n 1 -r user_input # -n 1 reads a single character, -r treats backslashes literally echo # Move to a new line after input case $user_input in [yY]) echo "User selected 'Yes'." # Place 'yes' logic here ;; [nN]) echo "User selected 'No'." # Place 'no' logic here ;; [cC]) echo "User selected 'Cancel'." # Place 'cancel' logic here ;; *) echo "Invalid choice." ;; esac
Explanation
read -n 1 -r
:-n 1
reads exactly one character (so the user doesn’t have to press Enter).-r
ensures raw input (backslashes aren’t processed).
- Case Insensitivity:
[yY]
,[nN]
, and[cC]
capture either uppercase or lowercase. - Line Break:
echo
afterread
just prints a newline for readability.
If you prefer the user to type a word like “yes” or “no,” you can omit -n 1
and read an entire string instead, then process it similarly in the case
.
Further Learning
Whether you’re refining shell scripting skills or preparing for coding interviews, consider these two valuable courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews
Develop a deep understanding of essential data structures and algorithms—useful for scripting efficiency and interview success. -
Grokking the Coding Interview: Patterns for Coding Questions
Master the key patterns behind algorithmic problems, giving you a clear edge when facing complex logic in shell scripts or larger codebases.
Combining robust Bash scripting with strong coding fundamentals sets you up for both day-to-day tasks and challenging software engineering problems alike.