mirror of
https://github.com/notwa/rc
synced 2024-11-05 02:29:06 -08:00
63 lines
1.7 KiB
Bash
Executable file
63 lines
1.7 KiB
Bash
Executable file
#!/usr/bin/env sh
|
|
# YES_ZSH
|
|
# YES_BASH
|
|
# YES_DASH
|
|
# YES_ASH
|
|
|
|
### @ confirm
|
|
### display a simple yes-or-no prompt and return 0-or-1 respectively.
|
|
###
|
|
### ```
|
|
### $ confirm && echo yay || echo nay
|
|
### Continue? [y/N] y
|
|
### yay
|
|
### $ confirm && echo yay || echo nay
|
|
### Continue? [y/N] n
|
|
### nay
|
|
### ```
|
|
###
|
|
### a real world example:
|
|
###
|
|
### ```
|
|
### $ g1 && confirm && git commit -a --amend --no-edit
|
|
### daf84e3 document a ton of stuff
|
|
### Continue? [y/N] y
|
|
### [master 92bdf76] document a ton of stuff
|
|
### Date: Sun Aug 1 09:27:25 2021 -0700
|
|
### 20 files changed, 406 insertions(+), 29 deletions(-)
|
|
### ```
|
|
|
|
# known inconsistencies:
|
|
# since the fallbacks pipe stderr into stdin,
|
|
# this will behave differently between zsh and non-zsh shells:
|
|
# ( echo hi | confirm | wc -c ) 2>/dev/null
|
|
|
|
if [ -n "$ZSH_VERSION" ]; then
|
|
confirm() {
|
|
[ $# -le 0 ] || { printf "%s\n" "$0: too many arguments" >&2; return 2; }
|
|
read -q '?Continue? [y/N] '
|
|
ret=$?
|
|
echo >/dev/tty
|
|
return $ret
|
|
}
|
|
elif [ -n "$BASH_VERSION" ]; then
|
|
confirm() {
|
|
[ $# -le 0 ] || { printf "%s\n" "$0: too many arguments" >&2; return 2; }
|
|
read -n1 -p "Continue? [y/N] " c
|
|
echo
|
|
[ "$c" = y ] || [ "$c" = Y ]
|
|
} <&2 >/dev/tty # try to ensure this is a terminal instead of a pipe
|
|
else
|
|
confirm() (
|
|
[ $# -le 0 ] || { printf "%s\n" "$0: too many arguments" >&2; return 2; }
|
|
old="$(stty -g)"
|
|
trap 'stty "$old"' INT EXIT
|
|
printf 'Continue? [y/N] '
|
|
stty -icanon
|
|
c="$(dd ibs=1 count=1 2>/dev/null)"
|
|
echo
|
|
[ "$c" = y ] || [ "$c" = Y ]
|
|
) <&2 >/dev/tty # try to ensure this is a terminal instead of a pipe
|
|
fi
|
|
|
|
[ -n "${preload+-}" ] || confirm "$@"
|