Last active
April 22, 2022 14:39
-
-
Save oscarkramer/2326ad1e1810dc98e91e817b02de662c to your computer and use it in GitHub Desktop.
Bash functions for prompting yes/no question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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