#!/usr/bin/env bash # YES_ZSH # YES_BASH # NO_DASH ### @ 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(-) ### ``` if [ -n "$ZSH_VERSION" ]; then confirm() { [ $# -le 0 ] || { printf "%s\n" "$0: too many arguments" >&2; return 1; } read -q '?Continue? [y/N] ' ret=$? echo return $ret } else confirm() { # specify stdin (1) to avoid taking input from pipes [ $# -le 0 ] || { printf "%s\n" "$0: too many arguments" >&2; return 1; } read -n1 -u 1 -p "Continue? [y/N] " c echo [ "$c" != 'y' ] && [ "$c" != 'Y' ] && return 1 return 0 } fi [ "${SOURCING:-0}" -gt 0 ] || confirm "$@"