BASH Programming

Getting Error in Bash Script; Expr $a + 1: Integer Expression Expected

Bash is a popular command-line interpreter that is commonly used in Linux and Unix-based systems as it allows users to execute commands and scripts in the terminal. One of the most common errors that users encounter when working with Bash is the “expr: integer expression expected” error. This article will take a closer look at this error, why it occurs, and how to correct it, so if you are facing the same error then read this guide.

What Is the “Expr: Integer Expression Expected” Error

The “expr: integer expression expected” error is an error message that is generated by the Bash shell when a user attempts to execute a mathematical expression that contains non-numeric characters. The error is typically accompanied by a line number that indicates where the error occurred in the script.

Why Does the “Expr: Integer Expression Expected” Error Occur

The “expr: integer expression expected” error occurs when the user attempts to perform a mathematical operation using non-numeric values. For example, if a user attempts to add a string to a number, the Bash shell will generate the “expr: integer expression expected” error. Let’s look at an example of faulty code that gives this error:

#!/bin/bash
a=0
b=3

while [ "$a" -lt $b ]
do
 echo $a
 a="expr $a + 1 "
done

 

Here the above code uses the while loop to carry on the addition process that compares the first variable, that is a whose value is 0, with the second variable b whose given value is 3. The loop will keep on executing till the condition gets false, that is a is less than b, the addition is carried out by using the expr command. The error message “expr $0 + 1: integer expression expected” indicates that there is a problem with the way the script is trying to increment the value of “a”. The error is caused by using double quotes instead of backticks or the dollar sign with parentheses to execute the “expr” command:

To fix the error, the script should use backticks (`) to execute the “expr” command and evaluate the arithmetic expression, so here is the correct code that uses the backticks:

#!/bin/bash

a=0
b=3

while [ "$a" -lt $b ]
do
 echo $a
 a=`expr $a + 1`
done

 

Here I have just replaced the double quotes with the backticks and now the expr command takes a as a integer and performs addition this the condition in the while loop gets false:

Conclusion

The “expr: integer expression expected” error is a common error that occurs in Bash when users attempt to perform mathematical operations on non-numeric values. To correct this error, it is important to make sure that all values in our mathematical expressions are numeric. By doing so, we can avoid this error and ensure that our scripts are executed as intended.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.