#!/bin/sh question=$1 default_answer=$(echo $2 | tr a-z A-Z) # Capitalize the default answer and construct the prompt if [ "$default_answer" = "Y" ]; then prompt="${question} (Y/n)? " else prompt="${question} (y/N)? " fi # Handle Ctrl-C trap "printf '\n'; exit 2" 2 # Use stty to make read command work for single character input old_stty_cfg=$(stty -g) stty raw -echo printf "%s" "$prompt" >&2 answer=$( while ! head -c 1 | grep -i '[yn]'; do true; done ) stty "$old_stty_cfg" >&2 # If no answer is given, use the default answer if [ -z "$answer" ]; then answer=$default_answer fi # Print the answer and return appropriate exit code printf "%s\n" "$(echo $answer | tr a-z A-Z)" >&2 sleep 0.01 # Without this, answer gets overwritten by next echo if [ "$answer" = "Y" -o "$answer" = "y" ]; then exit 0 else exit 1 fi