Skip to content

Instantly share code, notes, and snippets.

@Strykar
Last active January 14, 2021 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Strykar/6f8fb57a6e811280c26d7437d6647a86 to your computer and use it in GitHub Desktop.
Save Strykar/6f8fb57a6e811280c26d7437d6647a86 to your computer and use it in GitHub Desktop.
Bash General-Purpose Yes/No Prompt Function ("ask")

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.

ask() {
local prompt default reply
if [[ ${2:-} = 'Y' ]]; then
prompt='Y/n'
default='Y'
elif [[ ${2:-} = 'N' ]]; then
prompt='y/N'
default='N'
else
prompt='y/n'
default=''
fi
while true; do
# Ask the question (not using "read -p" as it uses stderr not stdout)
printf '%s%n' "$1 [$prompt] "
# Read the answer (use /dev/tty in case stdin is redirected from somewhere else)
read -r reply </dev/tty
# Default?
if [[ -z $reply ]]; then
reply=$default
fi
# Check if the reply is valid
case "$reply" in
Y*|y*) return 0 ;;
N*|n*) return 1 ;;
esac
done
}
# EXAMPLE USAGE:
if ask "Do you want to do such-and-such?"; then
printf '%s\n' "Yes"
else
printf '%s\n' "No"
fi
# Default to Yes if the user presses enter without giving an answer:
if ask "Do you want to do such-and-such?" Y; then
printf '%s\n' "Yes"
else
printf '%s\n' "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
printf '%s\n' "Yes"
else
printf '%s\n' "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