In Bash, how to add “Are you sure [Y/n]” to any co

2019-01-12 14:19发布

In this particular case, I'd like to add a confirm in Bash for

Are you sure? [Y/n]

for Mercurial's hg push ssh://username@www.example.com//somepath/morepath, which is actually an alias. Is there a standard command that can be added to the alias to achieve it?

The reason is that hg push and hg out can sound similar and sometimes when I want hgoutrepo, I may accidentlly type hgpushrepo (both are aliases).

Update: if it can be something like a built-in command with another command, such as: confirm && hg push ssh://... that'd be great... just a command that can ask for a yes or no and continue with the rest if yes.

16条回答
Root(大扎)
2楼-- · 2019-01-12 14:54

To avoid explicitly checking for these variants of 'yes' you could use the bash regular expression operator '=~' with a regular expression:

read -p "Are you sure you want to continue? <y/N> " prompt
if [[ $prompt =~ [yY](es)* ]]
then
(etc...)

That tests whether the user input starts with 'y' or 'Y' and is followed by zero or more 'es's.

查看更多
不美不萌又怎样
3楼-- · 2019-01-12 14:56

Add the following to your /etc/bashrc file. This script adds a resident "function" instead of an alias called "confirm".


function confirm( )
{
#alert the user what they are about to do.
echo "About to $@....";
#confirm with the user
read -r -p "Are you sure? [Y/n]" response
case "$response" in
    [yY][eE][sS]|[yY]) 
              #if yes, then execute the passed parameters
               "$@"
               ;;
    *)
              #Otherwise exit...
              echo "ciao..."
              exit
              ;;
esac
}
查看更多
We Are One
4楼-- · 2019-01-12 14:57

Late to the game, but I created yet another variant of the confirm functions of previous answers:

confirm ()
{
    read -r -p "$(echo $@) ? [y/N] " YESNO

    if [ "$YESNO" != "y" ]; then
        echo >&2 "Aborting"
        exit 1
    fi

    CMD="$1"
    shift

    while [ -n "$1" ]; do
        echo -en "$1\0"
        shift
    done | xargs -0 "$CMD" || exit $?
}

To use it:

confirm your_command

Features:

  • prints your command as part of the prompt
  • passes arguments through using the NULL delimiter
  • preserves your command's exit state

Bugs:

  • echo -en works with bash but might fail in your shell
  • might fail if arguments interfere with echo or xargs
  • a zillion other bugs because shell scripting is hard
查看更多
我命由我不由天
5楼-- · 2019-01-12 14:57

This may be a little too short, but for my own private use, it works great

read -n 1 -p "Push master upstream? [Y/n] " reply; 
if [ "$reply" != "" ]; then echo; fi
if [ "$reply" != "n" ]; then
    git push upstream master
fi

The read -n 1 just reads one character. If it's not a lowercase 'n', it is assumed to be a 'Y'.

(as for the real question: make that a bash script and change your alias to point to that script instead of what is was pointing to before)

查看更多
登录 后发表回答