Skip to content

Instantly share code, notes, and snippets.

@blacklabssecurity
Created September 2, 2018 23:41
Show Gist options
  • Select an option

  • Save blacklabssecurity/197da0b0dbc733d20723c835836a9b37 to your computer and use it in GitHub Desktop.

Select an option

Save blacklabssecurity/197da0b0dbc733d20723c835836a9b37 to your computer and use it in GitHub Desktop.
Yes / No Function for bash
#!/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.
ask() {
local prompt default reply
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 (not using "read -p" as it uses stderr not stdout)
echo -n "$1 [$prompt] "
# Read the answer (use /dev/tty in case stdin is redirected from somewhere else)
read 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
}
# Default to Yes if the user presses enter without giving an answer:
if ask "Do you want to configure this setting?" Y; then
echo "Yes"
else
echo "No"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment