Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Unary Operator Expected

Tags:

bash

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
like image 641
ThePGtipsy Avatar asked Mar 20 '13 11:03

ThePGtipsy


People also ask

What is unary operator expected?

Here, due to the blank value in the variable, the left side of the comparison expression disappears. In effect, we're left with a single argument for the equality check (eq) operator. The eq operator is a binary operator and needs two arguments, therefore, Bash complains with “unary operator expected”.

How do I put sleep in a bash script?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

Is not equal to in bash?

The not equal function in Ubuntu bash is denoted by the symbol “-ne,” which would be the initial character of “not equal.” Also included is the “! =” operator that is used to indicate the not equal condition.

Is variable empty bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"


1 Answers

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".

like image 70
kamituel Avatar answered Oct 18 '22 23:10

kamituel