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

前端 未结 17 2965
轮回少年
轮回少年 2020-11-29 15:11

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//some

17条回答
  •  情歌与酒
    2020-11-29 15:33

    Here is my solution that using localised regex. So in german also "j" for "Ja" would be interpreted as yes.

    First argument is the question, if the second argument is "y" than yes would be the default answer otherwise no would be the default answer. The return value is 0 if the answer was "yes" and 1 if the answer was "no".

    function shure(){
        if [ $# -gt 1 ] && [[ "$2" =~ ^[yY]*$ ]] ; then
            arg="[Y/n]"
            reg=$(locale noexpr)
            default=(0 1)
        else
            arg="[y/N]"
            reg=$(locale yesexpr)
            default=(1 0)
        fi
        read -p "$1 ${arg}? : " answer
        [[ "$answer" =~ $reg ]] && return ${default[1]} || return ${default[0]}
    }
    

    Here is a basic usage

    # basic example default is no
    shure "question message" && echo "answer yes" || echo "answer no"
    # print "question message [y/N]? : "
    
    # basic example default set to yes
    shure "question message" y && echo "answer yes" || echo "answer no"
    # print "question message [Y/n]? : "
    

提交回复
热议问题