Bash Scripting
User Input
Confirmation Prompt
Script Automation
Command Line Interface

How do I prompt a user for confirmation in bash script?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When writing scripts in Bash, you often need situations where user confirmation is needed before proceeding with an operation. This can be crucial for operations that are destructive in nature (like deleting files) or those that require a definite agreement from the user. In this article, we provide different methods to prompt for user confirmation and effectively handle the response in a Bash script.

Using read Command

The simplest approach to get user input in Bash is with the read command. This command pauses script execution and waits for user input.

Basic Confirmation Prompt

Here is a basic example of how to use read to prompt for a yes/no confirmation:

bash
1echo "Do you wish to continue? (y/n)"
2read answer
3
4case $answer in
5    [Yy]* ) echo "Proceeding...";;
6    [Nn]* ) echo "Operation aborted."; exit;;
7    * ) echo "Invalid input.";;
8esac

In this script:

  • read answer stores the user input into the variable answer.
  • The case statement then checks the first character of the input. It allows any word starting with 'Y' or 'y' to continue, and any starting with 'N' or 'n' to abort. Any other input results in an "Invalid input" message.

Improving the User Experience

To refine the user experience, you can use:

  • -p to add a prompt message directly in the read command.
  • -n 1 to accept a single character input, so that the user doesn’t need to hit ENTER.
  • -r to prevent backslashes from being interpreted as escape characters.

Example:

bash
1read -p "Do you wish to continue? (y/n) " -n 1 -r
2echo   # move to a new line
3if [[ $REPLY =~ ^[Yy]$ ]]
4then
5    echo "Proceeding..."
6else
7    echo "Operation aborted."
8    exit
9fi

In this script:

  • The use of [[ $REPLY =~ ^[Yy]$ ]] checks if the input is either 'Y' or 'y'.

Making It a Function

For reusability, encapsulate confirmation logic into a function:

bash
1confirm() {
2    while true; do
3        read -p "$1 (y/n): " -n 1 -r
4        echo    # new line
5        case $REPLY in
6            [Yy] ) return 0;;
7            [Nn] ) return 1;;
8            * ) echo "Invalid response.";;
9        esac
10    done
11}
12
13if confirm "Are you sure"; then
14    echo "Confirmed!"
15else
16    echo "Cancelled."
17fi

This function repeats the prompt until a valid response is received, which can be particularly useful for critical operations.

Best Practices and Accessibility

Error Handling and Validation

Ensure to validate the input comprehensively to handle unexpected inputs and behavior, which can be enhanced by specific regular expressions or additional case scenarios.

Internationalization

For scripts used in multiple regions, consider internationalizing the "yes" and "no" responses to match local languages and conventions.

Visual Feedback

For crucial operations, provide clear, visual feedback about the action that was confirmed. Optionally, implement a timed out default action using read -t.

Summary Table

FeatureOptionDescription
Prompt customization-pPrompts user with inline text.
Input limit-n 1Accepts a specific character count.
Raw input-rDisables escape character interpretation.
Timed response-t <sec>Limits wait time for user input.

By adopting these strategies, you can enhance both the user experience and the robustness of your bash scripts when confirming critical operations.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions