Last active
November 9, 2020 21:01
-
-
Save kfox/cf676aaef9c4173852b46dfc89837fae to your computer and use it in GitHub Desktop.
Bash function to prompt for yes or no with a single keypress
This file contains 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
#!/usr/bin/env bash | |
affirmative_response_to() { | |
PROMPT=$* | |
IFS= read -n 1 -s -p "${PROMPT}? [Y/n]: " answer | |
if [ "${answer:-Y}" = "${answer#[Yy]}" ]; then | |
# anything other than enter, Y, or y was pressed | |
echo "NO" | |
return 1 | |
fi | |
# enter, Y, or y was pressed | |
echo "YES" | |
} | |
if affirmative_response_to "Would you like some cake"; then | |
echo "Here is some cake for you!" | |
else | |
echo "FINE! I didn't want to share, anyway." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment