Bash (Scripting) - Resolve "unary operator expected"

by
Jeremy Canfield |
Updated: November 06 2023
| Bash (Scripting) articles
Let's say the following is being returned when invoking a bash shell script.
example.sh: line 1: [: ==: unary operator expected
This output is returned when a comparison (typically in an if statement) contains a variable that has not been defined (variable does not exist) or a variable that contains no value.
Here is an example script that will produce this ouput. In this example, the foo variable does not exist.
#!/bin/bash
if [ $foo == "bar" ]; then
exit
fi
In this example, the foo variable has been defined (exists) but contains no value.
#!/bin/bash
foo = ""
if [ $foo == "bar" ]; then
exit
fi
This can be resolved by adding a clause to the if statement to only invoke the if statement when the variable is not null.
#!/bin/bash
if [ ! -z $foo ] && [ $foo == "bar" ]; then
exit
fi
Did you find this article helpful?
If so, consider buying me a coffee over at