Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix bash error - binary operator expected

So below is the code i have in my bash script. I'm getting an error saying binary operator expected when i give the command 2 arguments (doesnt give error when i give 1 argument). It does change the file permissions when i give 2 arguments because i can see it when i do ls -l but it still gives me this error. How do i fix it?

for file in $@
do
    chmod 755 $file
done

if [ -z $@ ]
then
        echo "Error. No argument."
        exit $ERROR_CODE_1
fi

i have added this now

if [ ! -f "$*" ]
then
       echo "Error. File does not exist"
       exit $ERROR_NO_FILE
fi

But now when i enter more than 1 argument it just does everything in the if statement (i.e. prints error.file does not exist) even when the file does exist.

like image 817
pogba123 Avatar asked May 09 '26 13:05

pogba123


1 Answers

Doing it another way: just ask how many parameters were passed:

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

You get the error in your code because the $@ variable expands to multiple words, which leaves the test command looking like this:

[ -z parm1 parm2 parm3 ... ]

like image 193
Jeff Schaller Avatar answered May 12 '26 11:05

Jeff Schaller