Skip to content

Instantly share code, notes, and snippets.

@np
Last active December 14, 2015 15:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save np/5107721 to your computer and use it in GitHub Desktop.
Save np/5107721 to your computer and use it in GitHub Desktop.
A shell function to ask the user to answer a Yes/No question.
# asking() @ https://gist.github.com/np/5107721#file-asking-sh {{{
# Dependencies:
# error() @ https://gist.github.com/np/3736727#file-error-sh
# Options:
# --default=no Makes No being the default (--default=yes is the default)
# --no-slmenu Do no use slmenu even if available
# Examples:
# asking 'Something failed, do you still want to continue?'
# asking --default=yes 'Next step?'
asking(){
local default=0
local fzf=1
local slmenu=1
while true; do
case "$1" in
--default=yes) shift;;
--default=no) shift; default=1;;
--no-slmenu) shift; slmenu=0;;
--no-fzf) shift; fzf=0;;
--*) error 1 "asking: unexpected option argument $1";;
*) break;;
esac
done
if (( default )); then
local prompt_answer='y/N'
local prompt_answer_lines="$(printf 'No\nYes\n')"
else
local prompt_answer='Y/n'
local prompt_answer_lines="$(printf 'Yes\nNo\n')"
fi
printf '\a'
if (( slmenu )) && which slmenu >/dev/null 2>/dev/null; then
answer="$(slmenu -i -l 2 -p "$*" <<<"$prompt_answer_lines")"
elif (( fzf )) && which fzf >/dev/null 2>/dev/null; then
answer="$(fzf -1 --prompt="$* " <<<"$prompt_answer_lines")"
else
read -p "$* ($prompt_answer)" answer
fi
case "$answer" in
n|N|no|NO|No|nO) return 1;;
y|Y|yes|YES|Yes|YEs|YeS|yES|yeS|yEs) return 0;;
*) return $default;;
esac
}
check-positive-asking(){
while asking "$@"; do
echo "Good you can try another option or hit the opposite to leave this loop"
done
echo "You left the loop by typing the opposite, right?"
}
check-negative-asking(){
while true; do
if asking "$@"; then
break
else
echo "Good you can try another option or hit the opposite to leave this loop"
fi
done
echo "You left the loop by typing the opposite, right?"
}
check-asking(){
check-positive-asking 'hit y|Y|yes|YES|Yes|YEs|YeS|yES|yeS|yEs|nothing|garbage and hit RETURN'
check-negative-asking 'hit n|N|no|NO|No|nO and hit RETURN'
check-positive-asking --default=no 'hit y|Y|yes|YES|Yes|YEs|YeS|yES|yeS|yEs and hit RETURN'
check-negative-asking --default=no 'hit n|N|no|NO|No|nO|nothing|garbage and hit RETURN'
}
# }}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment