Skip to content

Instantly share code, notes, and snippets.

@kfox
Last active November 9, 2020 21:01
Show Gist options
  • Save kfox/cf676aaef9c4173852b46dfc89837fae to your computer and use it in GitHub Desktop.
Save kfox/cf676aaef9c4173852b46dfc89837fae to your computer and use it in GitHub Desktop.
Bash function to prompt for yes or no with a single keypress
#!/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