[Fixed] “integer expression expected” Error in Bash - LinuxSimply (2024)

The “integer expression expected” error is one of the common errors Bash users encounter. This error often arises when the shell expects an integer value but receives something else. Fortunately, understanding and rectifying this issue is not a big deal. In this article, I will talk about the subtlety of the “integer expression expected” error, providing you with insights and solutions to tackle the error.

Files of Integer Expression Expected Error in Bash

Table of Contents Expand

Reason for “integer expression expected” Error

The main reason of the “integer expression expected” error is the selection of the wrong operator or operand. This error is common in test statements that contain integers. Bash shell throws the error, when it evaluates an expression or a condition or works with a variable that is expected to contain integer numbers but does not meet the expected value. Look at the following example where the user utilizes the -eq operator to compare two strings:

#!/bin/bashstr1="Hello world"str2="Hello world"if [ "$str1" -eq "$str2" ];then echo "Strings Are Equal"fi

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (1)The script tries to compare whether str1 and str2 are equal or not using the -eq operator. However, it raises the “integer expression expected” error in line 4 because -eq expects two integer numbers to compare not strings. This is an archetype of wrong operand choice around the comparison operators that leads to “integer expression expected” error.

Scenarios Triggered “integer expression expected” Error

The root cause of the “integer expression expected” error remains the same in most cases. Nonetheless, various scenarios can trigger the error where it is difficult to find out the actual cause. Therefore, users need to be savvy enough to handle the error in different situations.

1. Error in Taking the Output of a Command

“integer expression expected” may occur due to syntax error while taking command output. For instance, users often end up with this error while using the expr command. This happens when someone tries to capture the output of the command and compare it with a value. But expr echos the expression itself if there is no space before and after the operator used within the command. The returned expression is a string and raises the “integer expression expected” error when compared with a number. Look at the following code to have a clear idea:

#!/bin/bashif [ $(expr 10%2) -eq 0 ]; thenecho "10 is divisible by 2"elseecho "10 is not divisible by 2"fi

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (2)The error occurred in line 2 of the above code. $(expr 10%2) was trying to capture the remainder when 10 is divided by 2. Instead of providing 0 as the remainder, it returned “10%2” due to the missing space before and after the modulo operator (%).

Now, when if [ $(expr 10%2) -eq 0 ] compared the output of expr with 0, it tried to determine whether the string “10%2” is equal to 0. Since the left-side operand of the -eq operator is expected to be an integer, Bash raised the “integer expression expected” error.

2. Error Due to Comparison of Floating Point Number With Integer

Bash Shell performs integer arithmetic. Hence, the comparison operators expect integers on both sides. Attempting to compare a floating-point number with an integer using a test statement will result in the “integer expression expected” error. For example, comparing whether 5 is greater than 0 is valid, but comparing 5.44 with 0 will trigger the error. See the example below:

#!/bin/bashnum=5.44if [ $num -gt 0 ];thenecho "The number is greater than zero"fi

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (3)It is evident that the error in line 3 occurs due to the comparison between floating number 5.44 and integer 0. Like 0 on the right side, Shell expects an integer on the left side as well. As 5.44 is not an integer Bash throws “integer expression expected”.

3. Incorrect Variable Referencing

Another major fault that raises the “integer expression expected” error is incorrect variable referencing. Sometimes users forget the proper syntax of variable referencing in Bash. In other instances, it occurs due to negligence. Think about the following example where the user failed to refer to a variable properly:

#!/bin/bashecho "Write in your age:"read ageif [ age -le "18" ]thenecho "Access Denied"elseecho "Access Granted"fi

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (4)The reference to the variable age in line 3 is incorrect. The dollar sign is missing at the beginning of the variable name. Consequently, -le compares the number 18 with the string “age” itself, not the variable’s value. -le expects integer value on both sides of the operator but found the string “age” on the left side.

How to Fix “integer expression expected” Error in Bash

Lots of buggy codes have been discussed so far. Now come to the solutions. To resolve the “integer expression expected” error, check the operator and operands used in the comparison. Also, be cautious when comparing floating point numbers.

1. Check the Operator and Operands

Consider the first code of this article again where -eq is used to compare two strings. The correct operator choice to avoid the “integer expression expected” error of this code should be = not -eq. Run the code again after replacing the operator:

#!/bin/bashstr1="Hello world"str2="Hello world"if [ "$str1" = "$str2" ]; then echo "Strings Are Equal"fi

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (5)As you can see this time the program works perfectly. It shows a message that two strings are equal.

2. Make a Valid Comparison

Again think about the code of wrong variable referencing or comparison that includes error in command output. These are mainly not a valid comparison. To fix the “integer expression expected” error of these codes, make sure the comparisons are valid and an integer is compared with another.

Let’s fix the error in expr command by placing space before and after the modulo operator:

#!/bin/bashif [ $(expr 10 % 2) -eq 0 ]; thenecho "10 is divisible by 2"fi

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (6)Now, the code captures the integer output of the expr command and successfully compares it with zero.

Conclusion

In summary, resolving the “integer expression expected” error becomes easy once you identify the cause. Nonetheless, to correct the error it is important to check the variables of numerical comparisons and values in mathematical expressions. I believe this article helps in diagnosing the error and finding the proper solution.

People Also Ask

Which commands in Bash are responsible for the “integer expression expected” error?

Any Bash command can be responsible for the “integer expression expected” error. But expr, let, bc etc. frequently raise this error as they deal with numbers.

How does Bash Shell recognize integer numbers?

Bash recognizes integer numbers contextually. Whenever you store a number in a Bash variable, it is considered a string. Now if you perform math or make a comparison using that variable, Bash parses the string into an integer. Moreover, it converts the result back to a string for storage.

How to convert a floating point number into an integer in Bash?

To convert a floating point number into an integer in Bash, use parameter expansion. For instance, ${float%.*} removes all the digits after the decimal point of the number stored in the variable named float. This essentially converts the floating point number into an integer.

float=1.23int=${float%.*}

Furthermore, you can use the printf command. “%.0f” format specifier defines the decimal precision to zero which means no digit after the decimal point.

float=1.23printf "%.0f" "$float"

How can I compare two floating point numbers in Bash?

You can compare two floating point numbers in Bash using the bc command. Let’s say you have two floating point numbers in num1 and num2 variables. Now, to determine whether num1 is greater than num2, use the code below:

#!/bin/bashread -p "Enter the first number:" num1read -p "Enter the first number:" num2if (( $(echo "$num1 > $num2" | bc -l) )); thenecho "$num1 is greater than $num2"elseecho "$num1 is less than $num2"fi

Does space around “[“ or “]” cause the “integer expression expected” error in Bash?

No. Missing space around “[“ or “]” causes error. But it doesn’t throw the “integer expression expected” error. In most of the cases, it raises the “command not found” or “missing ]” error.

Why should I use “[[” instead of “[” for comparison?

You should use “[[” instead of “[” for comparison if the variable you are working with contains spaces or other special characters. Variables may split into multiple words while using single square brackets (shortcut for the test command). Each of the words is then treated as a separate argument that causes the “too many arguments” error.

On the other hand, if you use double square brackets it may not serve your purpose exactly but it doesn’t raise errors in the console. A syntactical example can look like this:

#!/bin/bashVAR=$(Command_Name);if [[ $VAR == 0 ]]; then# some command or actionfi

float=1.23int=${float%.*}BashFurthermore, you can use the printf command. “%.0f” format specifier defines the decimal precision to zero which means no digit after the decimal point.

float=1.23printf \"%.0f\" \"$float\"" } },{ "@type": "Question", "name": "How can I compare two floating point numbers in Bash?", "acceptedAnswer": { "@type": "Answer", "text": "You can compare two floating point numbers in Bash using the bc command. Let’s say you have two floating point numbers in num1 and num2 variables. Now, to determine whether num1 is greater than num2, use the code below:

#!/bin/bashread -p \"Enter the first number:\" num1read -p \"Enter the first number:\" num2if (( $(echo \"$num1 > $num2\" | bc -l) )); thenecho \"$num1 is greater than $num2\"elseecho \"$num1 is less than $num2\"fi" } },{ "@type": "Question", "name": "Does space around “[“ or “]” cause the “integer expression expected” error in Bash?", "acceptedAnswer": { "@type": "Answer", "text": "No. Missing space around “[“ or “]” causes error. But it doesn’t throw the “integer expression expected” error. In most of the cases, it raises the “command not found” or “missing ]” error." } },{ "@type": "Question", "name": "Why should I use “[[” instead of “[” for comparison?", "acceptedAnswer": { "@type": "Answer", "text": "You should use “[[” instead of “[” for comparison if the variable you are working with contains spaces or other special characters. Single square brackets (shortcut for the test command) may split out into multiple words. Each of the words is then treated as a separate argument that causes the “too many arguments” error.

On the other hand, if you use double square brackets it may not serve your purpose exactly but it doesn’t raise errors in the console. A syntactical example can look like this:

#!/bin/bashVAR=$(Command_Name);if [[ $VAR == 0 ]]; then# some command or actionfi" } }]}

Related Articles

  • Performing Math Operations in Bash [12+ Commands Explained]
  • How to Calculate in Bash [3 Practical Examples]
  • How to Sum Up Numbers in Bash [Explained With Examples]
  • How to Divide Two Numbers in Bash [8 Easy Ways]
  • Division of Floating Point Numbers in Bash
  • How to Use “Mod” Operator in Bash [5 Basic Usage]
  • How to Format Number in Bash [6 Cases]
  • How to Generate Random Number in Bash [7 Easy Ways]
  • How to Convert Hexadecimal Number to Decimal in Bash
  • [Solved] “binary operator expected” Error in Bash

<< Go Back to Arithmetic Operators in Bash | Bash Operator | Bash Scripting Tutorial

5/5 - (3 votes)

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (7)

[Fixed] “integer expression expected” Error in Bash - LinuxSimply (2024)

References

Top Articles
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 5901

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.