Monthly Archives: November 2016

User input in shell script

I needed to write a small shell script which would allow me to make some decision based on user choices. I needed the user to specify Yes, No or Cancel for an operation. The following piece of hack does the job well.

#! /bin/bash

# define constants
declare -r TRUE=0
declare -r FALSE=1

user_choice() {
local str="$@"
while true
# Prompt user, and read command line argument
read -p "$str " answer

# Handle the input we were given
case $answer in
[yY]* ) return $TRUE;;

[nN]* ) return $FALSE;;

[cC]* ) exit;;

* ) echo "Y - Yes, N - No, C - Cancel. Please choose valid option.";;

if user_choice "Execute Job 1? "; then
echo "Executing Job 1.."
if user_choice "Execute Job 2? "; then
echo "Executing Job 2.."

The following links were referred to achieve this little script: