[Solved] “binary operator expected” Error in Bash

“binary operator expected” is one of the errors Bash users often face. This happens around the test statement or “[[” construction due to multiple reasons. In this article, I will talk about the causes of “binary operator expected” error as well as techniques to tackle the error.

What Does the “binary operator expected” Error Mean?

The “binary operator expected” is an error that occurs when Shell tries to evaluate a condition or expression that lacks necessary comparison operators or binary operators. Bash often uses conditionals such as if statements for decision-making. The conditionals heavily rely on binary operators to determine true or false outcomes. Once these operators are not placed properly Shell raises an error called “binary operator expected”.

Causes of “binary operator expected” Error in Bash

There are 2 main causes of the “binary operator expected” error. First, it is caused by unquoted variables. Second, it is due to the use of incorrect binary operators by novice users. Now, I am going to dive deep into the causes of the error. Then I will show you the solutions to this issue.

1. Incorrect Binary Operator in Conditional Statement

Binary operators in Bash are different from many other languages. For instance, the less-than-equal operator in Bash is -le not le or <=. If someone uses le instead of -le to make a comparison then it raises the “binary operator expected” error. The same goes for other binary operators. Look at the following code where the error is made by placing le instead of -le in the while loop:

#!/bin/bash
n=5
i=0
while [ $i le $n ]
do
echo "No Error"
i=$((i+1))
done

binary operator expected error due to incorrect operatorThe error message shows that “binary operator expected” error occurs in line 4.

This problem becomes invisible when double hyphens(--) are placed in front of binary operators instead of single hyphens. Rewrite the above code which looks correct but raises the same error message:

#!/bin/bash
n=100
i=0
while [ $i –le $n ]
do
echo "No Error"
i=$((i+1))
done
Keep in mind that if the comparable variables contain any character then the issue won’t be “binary operator expected” rather it would be “integer expression expected”. Because the binary operators are supposed to work with numbers.

2. Word Splitting or Lack of Necessary Quoting

The occurrence of “binary operator expected” due to the lack of necessary quoting is more common. When word splitting occurs because of spaces or other special characters, Shell receives multiple arguments to compare but not enough binary operators. See the example below:

#!/bin/bash
var1=*.txt
if [ -f $var1 ]
then
echo "It’s a text file."
fi

binary operator expected error due to lack of quoteThe error occurs in line 3 of the above code. if [ -f $file ] statement tries to evaluate whether var1 is a file. If you look at the error message carefully the program actually finds one file find_replace.txt. But as var1 is *.txt, it can match multiple .txt files. Let’s find out how many matches are there:

ls *.txt

Checking the text files of the current directoryIt is evident that var1 matches 2 files- find_replace.txt and output.txt. Therefore, if [ -f $var1 ] statement becomes [ -f find_replace.txt output.txt ]. At this point, Bash receives multiple words (find_replace.txt and output.txt) to compare. Hence it throws the “binary operator expected” error.

Look at another scenario. Think about a string with space in it. Then try to check whether the string is empty or not. If not empty create a text file using that string:

#!/bin/bash

str="back up"

if [ ! -z $str ]
then
touch "${str}.txt"
fi

binary operator expected error due to word splitingAs you can see it is showing the same error. The reason is- str contains a space in its value. Even if it is quoted while assigning, it doesn’t check $str from splitting in if [ ! -z $str ] statement. So, inside the if statement $str is split into two words back and up. Therefore line 5 raises the “binary operator expected” error.

Tips to Resolve “binary operator expected” Error

To resolve the “binary operator expected” error first find out the root cause of it. If it is because of an incorrect operator then change the operator. On the other hand, if it is due to unquoted variables or unexpected word splitting then use proper quoting to check unintended word splitting.

1. Use Correct Operators

To fix the “binary operator expected” error, use the correct operator for comparison. For instance, replace le with -le to fix the first script of this article.

#!/bin/bash

n=5
i=0

while [ $i -le $n ]
do
echo "No Error"
i=$((i+1))
done

Correct operator use to fix binary operator expected errorThis time the code worked fine. It didn’t raise any error. It prints the “No Error” message until the i is greater than n.

2. Proper Quoting of Variables

To resolve “binary operator expected” error ensure the variables used in the test statement are properly quoted. Consider the script of creating a text file based on the string back up. Though the string is not empty, the previous code was unable to create the file. Now, quote the str variable inside the test statement and run the code again:

#!/bin/bash

str="back up"
if [ ! -z "$str" ]
then
touch "${str}.txt"
fi

Proper quoting to fix binary operator expected error.txt files of my current directory show that there is a file ‘back up.txt’. So the program works. The only drawback is the whole filename back up.txt is single-quoted.

To test the existence of a file properly quote the variable in which the filename is stored:

if [ -f "$file" ]; then

Double bracket “[[” is more versatile than “[” test statement. You don’t need to quote the filename variable while using the double bracket:

if [[ -f $file ]]; then

Conclusion

In conclusion, “binary operator expected” mainly occurs when users try to evaluate a comparison that is incorrectly written. To resolve this error look around the line in which it happens. After that, carefully check the operators and quoting of the variables used in the test statement of that line. I believe this article makes you a master at fixing up the “binary operator expected” error.

People Also Ask

What should I do if I encounter “binary operator expected” error?

If you encounter “binary operator expected” error go to the line in which the error occurs. Check the conditional statement and find the cause of the error. Based on the reason, take the necessary steps to resolve the issue.

How to exit when “binary operator expected” error occurs?

The set -e can help you catch and exit on errors, but it won’t specifically address or prevent “binary operator expected” error. set -e terminates the execution of a script based on the exit status of the last command. It means if the last executed command raises any error or the exit status of the last command is not zero, then the program immediately terminates.

Does space in the test statement cause “binary operator expected” error?

No. If someone doesn’t maintain proper spacing in a test statement of a Bash script then it doesn’t throw “binary operator expected” error. However, it is an issue in Bash script and raises other types of errors.

How to find help on “test” command of the Bash shell?

To find help on test command run help test or man test on the terminal. This will provide you with all the information you need about the test command.

How to evaluate multiple comparisons using test statement?

To evaluate multiple comparisons using the test statement, use multiple test statements and connect them logically with && or || operators. For instance, to determine whether a number is greater than a minimum value and less than a maximum value, use the code below:

#!/bin/bash

if [[ "num" -ge "$minval" ]] && [[ "num" -le "$max_val" ]]; then
echo "The number is greater than ${minval} and less than ${maxval}"
fi

Related Articles


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

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment