8

Okay, so within my script (this is my first time working with Bash) I am being met with two unary operator expected errors. The code itself is actually working fine, but it's presenting me with these errors at runtime:

[: !=: unary operator expected

For the line:

if [ ${netmask[1]} != "" ]; do

So for the first error, it's thrown when ${netmask[1]} is "" (null). I have tried multiple ideas and still can't get it to work without returning that error in the process.


I solved it by adding quotation marks (grrr)

if [ "${netmask[1]}" != "" ]; do
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ThePGtipsy
  • 129
  • 2
  • 2
  • 6
  • thanks, that helped fix my bug super fast. Explanation is about 2/3 of the way down this page, in case it's not obvious to anyone else http://linuxcommand.org/wss0100.php – craq Oct 24 '13 at 15:57
  • The canonical may be *["unary operator expected" error in Bash if condition](https://stackoverflow.com/questions/13617843/)* – Peter Mortensen Oct 05 '21 at 16:44

1 Answers1

7

If you want to check for the null value for a variable, use the -z operator:

if [ -z "${netmask[1]}" ]; then

On example:

VAR=""

if [ -z "$VAR" ]; then
  echo This will get printed
fi

Please note the parentheses around the variable: "$VAR".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kamituel
  • 34,606
  • 6
  • 81
  • 98
  • I tried that also, but it doesn't seem to work, instead it actually inverts the true and false values for the loop. ie, when it should be true it enters the else, and when it should be false it says it's true – ThePGtipsy Mar 20 '13 at 11:25
  • @ThePGtipsy - I think you have some other `${netmask[1]}` value than `""`. Look at the example in my answer - it actually works as expected. – kamituel Mar 20 '13 at 11:35
  • Yeah I'd actually done logically the opposite of what I wanted in the else loop, I could have shifted the code from the else into the if and it would have worked as desired, although now I have managed to get it working, see the revised OP. Thanks for the help anyway! – ThePGtipsy Mar 20 '13 at 11:37
  • Re *"Please note the parentheses around the variable"*: I don't see any parentheses. Do you mean something else (e.g., [square brackets](https://en.wikipedia.org/wiki/Bracket#Square_brackets))? Can you elaborate? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/15522055/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Oct 05 '21 at 16:49