Skip to content

Instantly share code, notes, and snippets.

@oscarkramer
Last active April 22, 2022 14:39
Show Gist options
  • Save oscarkramer/2326ad1e1810dc98e91e817b02de662c to your computer and use it in GitHub Desktop.
Save oscarkramer/2326ad1e1810dc98e91e817b02de662c to your computer and use it in GitHub Desktop.
Bash functions for prompting yes/no question
# Bash function to prompt terminal user for yes|no
# Author: Oscar Kramer
#
# If interactive shell, prompts user for confirmation considering optional default (Y|N) specified.
# The default is returned if <enter> is typed in lieu of a y|n character. The prompt is appended with
# " [Y|n]:" or " [y|N]:" depending on default provided.
#
# If not interactive, returns answerYes=1, answerNo=0
# Returns boolean
#
# Bash examples:
# if answerYes "Want to do something dangerous?" N; then
# doSomethingDangerous
# fi
# if answerNo "Continue running script?" Y; then
# exit 0
# fi
#
function answerYes {
# Check for non-interactive shell?
echo
local prompt default
prompt="[Y/n]"
default=0
if [ "$2" == "n" ] || [ "$2" == "N" ]; then
prompt="[y/N]"
default=1
fi
while true; do
read -n 1 -p "$1 ${prompt}: " yn
echo
if [ -n "$yn" ]; then
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
return 0;
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
return 1;
fi
else
return $default;
fi
done
}
function answerNo {
if answerYes $1 $2 ; then
return 1
fi
return 0
}
### Example usage ###
if answerYes "Can ya dig it?" Y; then
echo "You're in the groove, Jackson!"
else
echo "Don't be a square!"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment