Another way to avoid encountering the unary operator expected error on our terminal shell is to use the double “square” brackets at the start and end of the “if” condition while using the “-eq” comparison operator for any type of value. So, we did that as shown below.
What is the Bash Unary Operator Expected error? It's an error that occurs when Bash identifies a line in your script that contains a binary operator that is not applied to two arguments. When this happens Bash assumes that you want to use a unary operator instead and raises the Unary Operator Expected error.
The word unary is basically synonymous with “single.” In the context of mathematics, this could be a single number or other component of an equation. So, when Bash says that it is expecting a unary operator, it is just saying that you are missing a number in the script.
To check if two strings are equal in bash scripting, use bash if statement and double equal to== operator. To check if two strings are not equal in bash scripting, use bash if statement and not equal to!= operator.
If you know you're always going to use Bash, it's much easier to always use the double bracket conditional compound command [[ ... ]]
, instead of the POSIX-compatible single bracket version [ ... ]
. Inside a [[ ... ]]
compound, word-splitting and pathname expansion are not applied to words, so you can rely on
if [[ $aug1 == "and" ]];
to compare the value of $aug1
with the string and
.
If you use [ ... ]
, you always need to remember to double quote variables like this:
if [ "$aug1" = "and" ];
If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only
if [ = "and" ];
which is not a valid syntax. (It would also fail with a different error message if $aug1
included white space or shell metacharacters.)
The modern [[
operator has lots of other nice features, including regular expression matching.
It took me a while to find this, but note that if you have a spacing error, you will also get the same error:
[: =: unary operator expected
Correct:
if [ "$APP_ENV" = "staging" ]
vs
if ["$APP_ENV" = "staging" ]
As always, setting -x
debug variable helps to find these:
set -x
Try assigning a value to $aug1
before use it in if[]
statements; the error message will disappear afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With