Monthly Archives: January 2010

Adding Confirmation to bash

The Problem

Bash does not have a “confirm” command to solicit the user’s confirmation of an action. I realize that some commands, such as rm which can ask for the user’s confirmation via the -i flag, but many do not. In addition, when writing bash scripts, I often run into situations which requires the confirmation for a series of commands, not just a single one.

The Solution

I created a confirm command, really a bash function which we can include in our script. The interface for this function is simple: think of it as a stripped-down version of the echo command. Below is the contents of, where I defined the confirm function.

The Code

# ======================================================================
# Function: confirm
# Asks the user to confirm an action, If the user does not answer yes,
# then the script will immediately exit.
# Parameters:
# $@ - The confirmation message
# Examples:
# >  # Example 1
# >  # The preferred way to use confirm
# >  confirm Delete file1? && echo rm file1
# >  
# >  # Example 2
# >  # Use the $? variable to examine confirm's return value
# >  confirm Delete file2?
# >  if [ $? -eq 0 ]
# >  then
# >      echo Another file deleted
# >  fi
# >  
# >  # Example 3
# >  # Tell bash to exit right away if any command returns a non-zero code
# >  set -o errexit
# >  confirm Do you want to run the rest of the script?
# >  echo Here is the rest of the script
# ======================================================================

function confirm()
    echo -n "$@ "
    read -e answer
    for response in y Y yes YES Yes Sure sure SURE OK ok Ok
        if [ "_$answer" == "_$response" ]
            return 0

    # Any answer other than the list above is considerred a "no" answer
    return 1


To use the function, just save the contents of the file above and name it Before using the confirm command
in your script, include the


The examples above should provide enough information to get started. For comments,
suggestions, bugs report, please post a comment to this blog post.