FUNDAMENTALS A Complete Guide for Beginners
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.
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/bash
str1="Hello world"
str2="Hello world"
if [ "$str1" -eq "$str2" ];then
echo "Strings Are Equal"
fi
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/bash
if [ $(expr 10%2) -eq 0 ]; then
echo "10 is divisible by 2"
else
echo "10 is not divisible by 2"
fi
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/bash
num=5.44
if [ $num -gt 0 ];
then
echo "The number is greater than zero"
fi
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/bash
echo "Write in your age:"
read age
if [ age -le "18" ]
then
echo "Access Denied"
else
echo "Access Granted"
fi
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/bash
str1="Hello world"
str2="Hello world"
if [ "$str1" = "$str2" ]; then
echo "Strings Are Equal"
fi
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/bash
if [ $(expr 10 % 2) -eq 0 ]; then
echo "10 is divisible by 2"
fi
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.23
int=${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.23
printf "%.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/bash
read -p "Enter the first number:" num1
read -p "Enter the first number:" num2
if (( $(echo "$num1 > $num2" | bc -l) )); then
echo "$num1 is greater than $num2"
else
echo "$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/bash
VAR=$(Command_Name);
if [[ $VAR == 0 ]]; then
# some command or action
fi
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