Skip to content

Instantly share code, notes, and snippets.

@rawiriblundell
Last active January 12, 2022 09:03
Show Gist options
  • Select an option

  • Save rawiriblundell/7e8a26d8076ce09b6daa315389f822cd to your computer and use it in GitHub Desktop.

Select an option

Save rawiriblundell/7e8a26d8076ce09b6daa315389f822cd to your computer and use it in GitHub Desktop.
Simple one-char-triggered request for confirmation
# A function to prompt/read an interactive y/n response
# Stops reading after one character, meaning only 'y' or 'Y' will return 0
# _anything_ else will return 1
confirm() {
read -rn 1 -p "${*:-Continue} [Y/N]? "
printf -- '%s\n' ""
case "${REPLY}" in
([yY]) return 0 ;;
(*) return 1 ;;
esac
}
# For a version that features a timeout:
# A function to prompt/read an interactive y/n response
# Stops reading after one character, meaning only 'y' or 'Y' will return 0
# Any other character, or an optional timeout (-t|--timeout) will return 1
confirm() {
local confirm_args
case "${1}" in
(-t|--timeout)
confirm_args=( -t "${2}" )
set -- "${@:3}"
;;
esac
read "${confirm_args[@]}" -rn 1 -p "${*:-Continue} [Y/N]? "
printf -- '%s\n' ""
case "${REPLY}" in
([yY]) return 0 ;;
(*) return 1 ;;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment