Created
May 7, 2020 13:38
-
-
Save StoneLabs/ef6777d21acc7d85d4ef1cbc82c9888c to your computer and use it in GitHub Desktop.
Bash confirmation prompt
This file contains 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() { | |
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 | |
} | |
if ask "Confirm?" Y; then | |
echo "Yes." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment