Logo

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:

  1. Displaying a prompt (e.g., “y/n/c”)
  2. Reading a single character of user input
  3. 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 after read 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:

Combining robust Bash scripting with strong coding fundamentals sets you up for both day-to-day tasks and challenging software engineering problems alike.

CONTRIBUTOR
TechGrind