#!/bin/bash ## # Ask a Yes/No question, and way for a reply. # # 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. # # @param {string} prompt The question to ask the user. # @param {string} [default] Optional. "Y" or "N", for the default option to use if none is entered. # @param {int} [timeout] Optional. The number of seconds to wait before using the default option. # # @returns {bool} true if the user replies Yes, false if the user replies No. ## ask() { # Source: https://djm.me/ask local timeout endtime timediff prompt default reply while true; do timeout="${3:-}" if [ "${2:-}" = "Y" ]; then prompt="Y/n" default=Y elif [ "${2:-}" = "N" ]; then prompt="y/N" default=N else prompt="y/n" default= timeout= fi if [ -z "$timeout" ]; then # Ask the question (not using "read -p" as it uses stderr not stdout) echo -en "$1 [$prompt] " # Read the answer (use /dev/tty in case stdin is redirected from somewhere else) read reply /dev/null 2>&1 }