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.
Last active
August 29, 2015 13:58
-
-
Save tlamer/9929610 to your computer and use it in GitHub Desktop.
[bash] General purpose Yes/No function
This file contains hidden or 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
| ask() { | |
| while true; do | |
| if [ "${2:-}" = "Y" ]; then | |
| local prompt="Y/n" | |
| local default=Y | |
| elif [ "${2:-}" = "N" ]; then | |
| local prompt="y/N" | |
| local default=N | |
| else | |
| local prompt="y/n" | |
| local default= | |
| fi | |
| # Ask the question | |
| printf "$1 [$prompt] " | |
| read REPLY | |
| # 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 | |
| } |
This file contains hidden or 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
| if ask "Do you want to do such-and-such?"; then | |
| echo "Yes" | |
| else | |
| echo "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 | |
| 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