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

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

    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 usage
    prompt_confirm "Overwrite File?" || exit 0
    

    You can change the default prompt by passing an argument

提交回复
热议问题