The Bash logo, a hexagon with a shell prompt inside it, beside the words "Bash, the Bourne-Again Shell"
Back to Blog
DevOps & Infrastructure
April 5, 2020
Fahim Hossain

Bash Scripts - Prompt User Inputs, Validate and Perform Calculations

How to prompt for input in a Bash script, validate what comes back, and run a calculation on it without the whole thing falling over on bad data.

The Bash logo, a hexagon with a shell prompt inside it, beside the words "Bash, the Bourne-Again Shell"

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

Running infrastructure like this in production? ARITS does Kubernetes and DevOps platform engineering so your team can ship without babysitting servers.

Need extra engineers, or a team to run the build?

Tell us the shape of the work and your deadline. You will get a straight read on what it takes and what it will cost, from a team that has shipped 400+ projects out of Dhaka and London.

Cookies

We use cookies to see how people find this site and to measure our ads. You can turn those off — everything here still works. Privacy policy

Necessary

Keeps the site working and remembers this choice.

Always on

Analytics

Anonymous stats on which pages get read, so we know what to write next.

Marketing

Lets us measure which ads brought someone here.