Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script error [: !=: unary operator expected

Tags:

bash

In my script I am trying to error check if the first and only argument is equal to -v, but it is an optional argument. I use an if statement, but I keep getting the unary operator expected error.

This is the code:

if [ $1 != -v ]; then    echo "usage: $0 [-v]"    exit fi 

To be more specific:

This part of the script above is checking an optional argument and then after, if the argument is not entered, it should run the rest of the program.

#!/bin/bash  if [ "$#" -gt "1" ]; then    echo "usage: $0 [-v]"    exit fi  if [ "$1" != -v ]; then    echo "usage: $0 [-v]"    exit fi  if [ "$1" = -v ]; then    echo "`ps -ef | grep -v '\['`" else    echo "`ps -ef | grep '\[' | grep root`" fi 
like image 983
user3380240 Avatar asked Mar 04 '14 17:03

user3380240


People also ask

How do I fix unary operator expected?

To prevent this script from throwing the “unary operator expected” error on bash, we need to update the code once again. We have to add the double quotes around the left expression “$v,” as we have done in the image below. The rest of the code will be unchanged for now. Now, the code is ready for use.

What is unary operator in bash script?

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.

What does =~ mean in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.

What does $? Meaning in a bash script?

$? - It gives the value stored in the variable "?". Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) . Follow this answer to receive notifications. edited Jun 20, 2020 at 9:12. CommunityBot.


1 Answers

Quotes!

if [ "$1" != -v ]; then 

Otherwise, when $1 is completely empty, your test becomes:

[ != -v ] 

instead of

[ "" != -v ] 

...and != is not a unary operator (that is, one capable of taking only a single argument).

like image 121
Charles Duffy Avatar answered Oct 23 '22 12:10

Charles Duffy