1
0
Fork 0
mirror of https://github.com/notwa/rc synced 2024-06-26 09:07:12 -07:00
rc/sh/confirm

61 lines
1.6 KiB
Plaintext
Raw Normal View History

#!/usr/bin/env sh
2021-07-29 00:37:35 -07:00
# YES_ZSH
# YES_BASH
# YES_DASH
# YES_ASH
2021-07-29 00:37:35 -07:00
2021-07-30 17:57:08 -07:00
### @ 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
### ```
2021-08-01 09:45:19 -07:00
###
### a real world example:
###
### ```
### $ g1 && confirm && git commit -a --amend --no-edit
2021-08-01 09:45:19 -07:00
### 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(-)
### ```
2021-07-30 16:31:21 -07:00
if [ -n "$ZSH_VERSION" ]; then
2013-07-01 18:05:17 -07:00
confirm() {
2021-09-28 12:34:56 -07:00
[ $# -eq 0 ] || { printf "%s\n" "$0: too many arguments" >&2; return 2; }
local c=
read -q '?Continue? [y/N] ' c
2013-07-01 18:05:17 -07:00
ret=$?
echo >/dev/tty
2013-07-01 18:05:17 -07:00
return $ret
}
elif [ -n "$BASH_VERSION" ]; then
2013-07-01 18:05:17 -07:00
confirm() {
2021-09-28 12:34:56 -07:00
[ $# -eq 0 ] || { printf "%s\n" "$0: too many arguments" >&2; return 2; }
local c=
read -n1 -p "Continue? [y/N] " c 2>&1
2013-07-01 18:05:17 -07:00
echo
[ "$c" = y ] || [ "$c" = Y ]
} 1<>/dev/tty <&1 # ensure this interacts with a terminal instead of a pipe
else
confirm() (
2021-09-28 12:34:56 -07:00
[ $# -eq 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 ]
) 1<>/dev/tty <&1 # ensure this interacts with a terminal instead of a pipe
2013-06-28 05:22:14 -07:00
fi
2021-07-29 00:37:35 -07:00
[ -n "${preload+-}" ] || confirm "$@"