Skip to main content
update code to print a better message
Source Link

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

function confirm() {
  local response
  local 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
}
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.

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

function confirm() {
  local response
  local 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.

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.
Source Link

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

function confirm() {
  local response
  local 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.