Skip to content

Instantly share code, notes, and snippets.

@atika
Last active August 29, 2015 14:08
Show Gist options
  • Save atika/655e9a2fca3efaca6b56 to your computer and use it in GitHub Desktop.
Save atika/655e9a2fca3efaca6b56 to your computer and use it in GitHub Desktop.
This is a general-purpose function to ask Yes/No questions in Bash, either with or without a default answer.
#!/bin/bash
# This is a general-purpose function to ask Yes/No questions in Bash, either
# with or without a default answer. It keeps repeating the question until it
# gets a valid answer.
# http://djm.me/ask
while true; do
if [ "${2:-}" = "Y" ]; then
prompt="Y/n"
default=Y
elif [ "${2:-}" = "N" ]; then
prompt="y/N"
default=N
else
prompt="y/n"
default=
fi
# Ask the question
echo -ne "$1 [$prompt] "
read -n1 REPLY
echo
# Default?
if [ -z "$REPLY" ]; then
REPLY=$default
fi
# Check if the reply is valid
case "$REPLY" in
Y*|y*) exit 0 ;;
N*|n*) exit 1 ;;
esac
done
#/bin/bash
said_yes() { echo "Just said YES!"; }
said_no() { echo "Just said NO!"; }
# EXAMPLE USAGE:
if ask "Do you want to do such-and-such?"; then
echo "Yes"
else
echo "No"
fi
# Colored syntax:
ask "Do you want to do \\033[1;31msuch-and-such\\033[0m?" && said_yes
# Default to Yes if the user presses enter without giving an answer:
if ask "Do you want to do such-and-such?" Y; then
echo "Yes"
else
echo "No"
fi
# Default to No if the user presses enter without giving an answer:
if ask "Do you want to do such-and-such?" N; then
echo "Yes"
else
echo "No"
fi
# Only do something if you say Yes
if ask "Do you want to do such-and-such?"; then
said_yes
fi
# Only do something if you say No
if ! ask "Do you want to do such-and-such?"; then
said_no
fi
# Or if you prefer the shorter version:
ask "Do you want to do such-and-such?" && said_yes
ask "Do you want to do such-and-such?" || said_no
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment