Thursday, December 8, 2016

Error handling in shell script


Error handling in shell script while receiving user input

 
This is help full sample script that can help in error handling.In situations where I give user to choose 1 or 2 but lets say in rush/hurry user inputs a diff value. This script can handle those situations. In below script the user will be in loop until he passes a expected value (1 or 2 in this case). This script can be altered as per your requirement.

On how to handle just blank inputs use this link


-- Script starts here

#!bin/sh
## Created by     :    Arvind Toorpu
## This script will prompt user for input until the user passes the expected input.
##
while :
echo "enter value for a:";read -r a;  do
         if [ -z "${a}" ]; then
         echo "That was empty, do it again!"

        elif [ "${a}" -eq "1" ]  || [ "${a}" -eq "2" ]; then
                ## echo "Checking now..."
                echo "value passed is :$a"
                echo "Condition success"
         break

        elif [ "${a}" -ge "3" ]
        then
        echo "Select either option :1 or :2 "
    fi
##break
done


Sample output :

atoorpu@Linux01:[~/TEST_DIR/scripts] $ . Test_input2.sh
enter value for a:

That was empty, do it again!
enter value for a:

That was empty, do it again!
enter value for a:
4
Select either option :1 or :2
enter value for a:
5
Select either option :1 or :2
enter value for a:
6
Select either option :1 or :2
enter value for a:
6
Select either option :1 or :2
enter value for a:
7
Select either option :1 or :2
enter value for a:
2
value passed is :2
Condition success
do your thing here with read value 2

No comments:

Post a Comment