Skip to content

Instantly share code, notes, and snippets.

@criztovyl
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save criztovyl/3c09be4eecfef32dd31e to your computer and use it in GitHub Desktop.
Save criztovyl/3c09be4eecfef32dd31e to your computer and use it in GitHub Desktop.
Ask a Yes/No question and executes an action dependent on the answer
#!/bin/bash
# Asks a user a Yes/No question and executes actions dependent on the answer.
# Copyright (C) 2015 Christoph "criztovyl" Schulz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
function yesdo()
# Ask the user a question and executes an action dependent on answer.
# Defaults to yes.
#
# Usage: question action notaction
# question: the question asked ("[nY] " is appended)
# action: executed on yes
# notaction: executed on no.
{
#Variables
yes_lc="y"
question=$1" [nY] "
action=$2
notaction=$3
# Read single yes/no character
read -n 1 -p "$question" char
# Determine answer and executes action on yes (y or Y) or on nothing (newline)
# Also determines if need to add a newline (if entered single character, not newline)
nl="\n"; [ -z "$char" ] && nl="" || [ "${char,,}" == "y" ] && echo -ne "$nl" && eval "$action" || { echo -ne "$nl"; [ "$notaction" ] && eval "$notaction"; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment