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
do
# 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.";;
esac
done
}

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

The following links were referred to achieve this little script:
http://linuxcommand.org/wss0090.php
https://bash.cyberciti.biz/guide/Returning_from_a_function
http://alvinalexander.com/linux-unix/shell-script-how-prompt-read-user-input-bash