stfudonny
stfudonny

Reputation: 53

bash script: [: ==: unary operator expected even though I'm almost sure my conditional syntax is right

Hello everyone I seem to be stuck on the "elif [ $1 == 0 ]" part of my script.

The purpose of this conditional statement is to exit if the user did not pass an argument to my script.

(if the user simply runs "sh safe_rm" instead of "sh safe_rm filename which is the intended behavior)

I'm still in the early stages of this script so it doesn't do anything so far, but I want to get the conditionals out of the way first, but I can't find out what I did wrong with elif [ $1 == 0 ] . I have also tried elif [ $1 -eq 0 ] and elif [ $1 == '' ] and none of them seem to be working

   # This checks whether the  $HOME/deleted/ exists. If it does not exist, it will get created. If it exists, nothing happens.
if [ ! -d $HOME/deleted/ ]
        then
                echo "/deleted/ directory does not exist. Creating it..."
                mkdir $HOME/deleted/
        else
        echo "Directory /Deleted/ already exists. Continuing..."
fi
# The conditional statements below check if the argument passed is a directory, or if it does not exist, or if nothing has been passed.
# All 3 cases will cause the program to quit since there is nothing to be done. The user needs to provide a file that exists.
if [ ! -e $1 ]
        then
                echo "File does not exist!"
                exit 1
elif [ $1 == 0 ]   #<---problem here I have also tried elif [ $1 -eq 0 ] and elif [ $1 == '' ]
        then
                echo "No filename has been provided!"
                exit 1
elif [ -d $1 ]
        then
                echo "This is a directory, not a file!"
                exit 1
elif [ $1 == 'safe_rm' ]
        then
                echo "Attempting to delete safe_rm. Operation aborted."
                exit 1
fi

Upvotes: 0

Views: 85

Answers (2)

Aaron
Aaron

Reputation: 24802

You should quote your arguments. In your case, when $1 is not set, the test expands to [ == 0 ], which is syntactically incorrect.

[ "$1" == 0 ] however would resolve to [ "" == 0 ], which is syntactically correct and return false.

It's still not what you want obviously, but jlliagre's answer provides that.

Upvotes: 2

jlliagre
jlliagre

Reputation: 30813

To test if the user passed no argument, the statement should be:

...
elif [ $# -eq 0 ]
...

Upvotes: 2

Related Questions