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

前端 未结 17 3015
轮回少年
轮回少年 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:37

    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

提交回复
热议问题