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

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

    This version allows you to have more than one case y or Y, n or N

    1. Optionally: Repeat the question until an approve question is provided

    2. Optionally: Ignore any other answer

    3. Optionally: Exit the terminal if you want

      confirm() {
          echo -n "Continue? y or n? "
          read REPLY
          case $REPLY in
          [Yy]) echo 'yup y' ;; # you can change what you do here for instance
          [Nn]) break ;;        # exit case statement gracefully
          # Here are a few optional options to choose between
          # Any other answer:
      
          # 1. Repeat the question
          *) confirm ;;
      
          # 2. ignore
          # *) ;;
      
          # 3. Exit terminal
          # *) exit ;;
      
          esac
          # REPLY=''
      }
      

    Notice this too: On the last line of this function clear the REPLY variable. Otherwise if you echo $REPLY you will see it is still set until you open or close your terminal or set it again.

提交回复
热议问题