Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting unexpected operator

Tags:

bash

shell

I'm writing script for git hook and have trouble with if statement inside while.

File:

#!/bin/sh
while read oldrev newref ref
do
    branch=$(git rev-parse --symbolic --abbrev-ref $ref)

    if [ "a"  == "a" ]
    then
        echo "Condition work"
    fi

    echo "$branch"
done

Error:

hooks/post-receive: 6: [: a: unexpected operator

I'll try with variables, double quotes but if doesn't work. What kind of error is here?

Thanks

like image 329
Sonique Avatar asked Jun 28 '14 07:06

Sonique


People also ask

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.

What does Unexpected end of file mean in bash?

An Unexpected end of file error in a Bash script usually occurs when you there is a mismatched structure somewhere in the script. If you forget to close your quotes, or you forget to terminate an if statement, while loop, etc, then you will run into the error when you try to execute your Bash script.

What is the difference between sh and bash?

bash is sh, but with more features and better syntax. Bash is “Bourne Again SHell”, and is an improvement of the sh (original Bourne shell). Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. sh is a shell command-line interpreter of Unix/Unix-like operating systems.

How do I write an if statement in bash?

The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword. If the TEST-COMMAND evaluates to True , the STATEMENTS gets executed. If TEST-COMMAND returns False , nothing happens; the STATEMENTS get ignored.


1 Answers

if [ "a" == "a" ] should be if [ "a" = "a" ].

bash accepts == instead of =, but your /bin/sh probably isn't bash.

So either change the == to =, or your shebang to #!/bin/bash

like image 161
mata Avatar answered Sep 23 '22 09:09

mata