In Bash, how to add "Are you sure [Y/n]" to any command or alias? In Bash, how to add "Are you sure [Y/n]" to any command or alias? bash bash

In Bash, how to add "Are you sure [Y/n]" to any command or alias?


These are more compact and versatile forms of Hamish's answer. They handle any mixture of upper and lower case letters:

read -r -p "Are you sure? [y/N] " responsecase "$response" in    [yY][eE][sS]|[yY])         do_something        ;;    *)        do_something_else        ;;esac

Or, for Bash >= version 3.2:

read -r -p "Are you sure? [y/N] " responseif [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]then    do_somethingelse    do_something_elsefi

Note: If $response is an empty string, it will give an error. To fix, simply add quotation marks: "$response". – Always use double quotes in variables containing strings (e.g.: prefer to use "$@" instead $@).

Or, Bash 4.x:

read -r -p "Are you sure? [y/N] " responseresponse=${response,,}    # tolowerif [[ "$response" =~ ^(yes|y)$ ]]...

Edit:

In response to your edit, here's how you'd create and use a confirm command based on the first version in my answer (it would work similarly with the other two):

confirm() {    # call with a prompt string or use a default    read -r -p "${1:-Are you sure? [y/N]} " response    case "$response" in        [yY][eE][sS]|[yY])             true            ;;        *)            false            ;;    esac}

To use this function:

confirm && hg push ssh://..

or

confirm "Would you really like to do a push?" && hg push ssh://..


Here is roughly a snippet that you want.Let me find out how to forward the arguments.

read -p "Are you sure you want to continue? <y/N> " promptif [[ $prompt == "y" || $prompt == "Y" || $prompt == "yes" || $prompt == "Yes" ]]then  # http://stackoverflow.com/questions/1537673/how-do-i-forward-parameters-to-other-command-in-bash-scriptelse  exit 0fi

Watch out for yes | command name here :)


Confirmations are easily bypassed with carriage returns, and I find it useful to continually prompt for valid input.

Here's a function to make this easy. "invalid input" appears in red if Y|N is not received, and the user is prompted again.

prompt_confirm() {  while true; do    read -r -n 1 -p "${1:-Continue?} [y/n]: " REPLY    case $REPLY in      [yY]) echo ; return 0 ;;      [nN]) echo ; return 1 ;;      *) printf " \033[31m %s \n\033[0m" "invalid input"    esac   done  }# example usageprompt_confirm "Overwrite File?" || exit 0

You can change the default prompt by passing an argument