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

前端 未结 17 2950
轮回少年
轮回少年 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条回答
  •  -上瘾入骨i
    2020-11-29 15:36

    Well, here's my version of confirm, modified from James' one:

    function confirm() {
      local response msg="${1:-Are you sure} (y/[n])? "; shift
      read -r $* -p "$msg" response || echo
      case "$response" in
      [yY][eE][sS]|[yY]) return 0 ;;
      *) return 1 ;;
      esac
    }
    

    These changes are:

    1. use local to prevent variable names from colliding
    2. read use $2 $3 ... to control its action, so you may use -n and -t
    3. if read exits unsuccessfully, echo a line feed for beauty
    4. my Git on Windows only has bash-3.1 and has no true or false, so use return instead. Of course, this is also compatible with bash-4.4 (the current one in Git for Windows).
    5. use IPython-style "(y/[n])" to clearly indicate that "n" is the default.

提交回复
热议问题