Menu

Category

Bash Scripts – Prompt User Inputs, Validate and Perform Calculations

April 5, 2020
Bash Scripts – Prompt User Inputs, Validate and Perform Calculations

While writing a Bash Script, sometimes it becomes important to prompt for user input, validate them and then perform some calculations. In this tutorial, let us take a quick look into reading and validating user inputs before performing a simple operation via a shell script.

Here is an outline of what we have planned out in this tutorial –

  1. Create a bash script which takes two input numbers
  2. Validate that the user has actually inserted numbers (integer or float)
  3. Add the two numbers (integer or float) and show the final result .

So, let us begin!

Step 1: Create a blank Bash Script File

Let us create a tutorial.sh file in the current directory from the terminal by typing in the following command –

touch tutorial.sh

Step 2: Set Correct Permission to the Shell Script File

Now we would need set the correct permission on the bash script file. Type the following command in the terminal to add the required execution permissions to the script file –

chmod +x  tutorial.sh

Step 3: Get User Input

Now open the shell script file and add in the following command to prompt the user to insert two numbers.

#! /bin/bash
#Prompt user to insert inputs (one at a time) 
read -p 'Enter Number 1: ' number1
read -p 'Enter Number 2: ' number2

Step 4: Validate User Input

Now before we add the two numbers, we need to validate two scenarios –

  • Make sure that the user not inserting blank inputs
  • Be certain that the user is inserting valid inputs (integer or float numbers)

If user is not inserting valid data, we will simply stop the execution of the script and display an informative error message. The following code snippet illustrates it further –

#! /bin/bash
#Prompt user to insert inputs (one at a time) 
read -p 'Enter Number 1: ' number1
read -p 'Enter Number 2: ' number2

#Firstly Validate if any input field is left blank
#If an input field is left blank, display appropriate message and stop execution of script 
if [ -z "$number1" ] || [ -z "$number2" ]
then
	echo 'Inputs cannot be blank please try again'
	exit 0
fi

#Now Validate if the user input is a number (Integer or Float)
#If an input field not a number, display appropriate message and stop execution of script
if ! [[ "$number1" =~ ^[+-]?[0-9]+\.?[0-9]*$ ]] || ! [[ "$number2" =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]
    then
        echo "Inputs must be a numbers"
		exit 0
fi

Step 4: Perform Calculation

After validating the user input, we can be certain that the inserted input is either an integer or a float. Now we will perform a simple addition of the two numbers.

The following code block shows the final shell script code which performs the addition operation of two user input number –

#! /bin/bash
#Prompt user to insert inputs (one at a time) 
read -p 'Enter Number 1: ' number1
read -p 'Enter Number 2: ' number2


#Firstly Validate if any input field is left blank
#If an input field is left blank, display appropriate message and stop execution of script 
if [ -z "$number1" ] || [ -z "$number2" ]
then
	echo 'Inputs cannot be blank please try again'
	exit 0
fi


#Now Validate if the user input is a number (Integer or Float)
#If an input field not a number, display appropriate message and stop execution of script
if ! [[ "$number1" =~ ^[+-]?[0-9]+\.?[0-9]*$ ]] || ! [[ "$number2" =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]
    then
        echo "Inputs must be a numbers"
		exit 0
fi

#Ok now we are sure that user has provided valid data
#Now Add the two numbers (integer or float)
total=$(echo "${number1} + ${number2}"| bc)
echo 'Summation Result '$total

Do let me know if you have questions! Thanks

Fahim Hossain

Fahim Hossain

With the booming pace of the tech industry, there is a lot to grasp, learn and master. My passion is to work with different architectural design patterns and developing high performance software solutions using the latest technology stacks. I am the founder of ARITS Limited and am currently serving as its Chief Executive Officer

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll
Advancing Through Technology
Ground Floor • House 375 • Lane 6W
Baridhara DOHS • Dhaka • 1206 • Bangladesh
Email : contact@aritsltd.com
Call: ‭+880 19 0519 9835
Automation • Robotics • Information • Technology • Solutions
© 2019 ARITS Limited • Advancing Through Technology
All rights reserved.