Confirm The Input

In many case, when developing a menu system using shell script, it will be good to prompt the user to confirm that it is okay to run a script.

for example:

Are you sure to run this task? [Yes | No]

Only reply with Yes will continue the action, else the script will exit or return to the menu.

This is useful when executing script that will perform critical tasks, such as rebooting server, stop/start application, purging files, and so on.

How to do that?

echo “Do you really want to run this job? [YES|NO]”
read answer
if [ -z “$answer” ]
then
answer=NULL
else
answer=`echo $answer|tr -s ‘[:lower:]’ ‘[:upper:]’`
fi

The first part of this script will prompt for user confirmation.
Empty input (just press ENTER key) will be set as NULL and all input will be converted to CAPITAL LETTER.

case $answer in
YES) echo “You have typed $answer.Execute the code now.”
echo “Insert your script here”
;;
NO) echo “You have typed $answer.”
echo “Exit the menu”
;;
*) echo “You have typed $answer.”
echo “Invalid Selection. Return to the menu”
;;
esac

Only reply with YES is allow to continue the script, otherwise it will return to the menu or exit the script.

Tested on AIX 5.1 and ksh environment.

I’m sure others have written similar script. Any comment ?

Posted in Shell Script Tagged with:

Leave a Reply