Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my Git hooks shell script result in a parse error?

I do little shell scripting so hopefully I am doing something obviously wrong!

This hook is intended to run whenever you push. If you are on the designated branch, in this case ‘githook’, it should run npm run testbuild and if that fails, stop the push.

If you are on another branch it should not interfere, and if you are on that branch and that test completes without error, it should let the push go ahead.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the content of the script pre-push:

#!/bin/zsh

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

CMD="npm run testbuild"

if [[ $current_branch = "githook"]]; then
    eCHO "You are on $branch, running build test"
    eval $CMD
    RESULT=$?
    if [ $RESULT -ne 0 ]; then
        echo "failed $CMD"
        exit 1
    fi
fi
exit 0

Currently, when I push from that branch, I get this:

.git/hooks/pre-push:7: parse error near `;’~

But I don’t see anything obviously wrong there?

>Solution :

You need to have whitespace before ]] so that it is recognized as a separate token. eg:

if [[ "$current_branch" = githook ]]; then

Note that there is no need to quote the bare string githook, but you should always quote variables unless you have a reason not to. (Within [[, it’s not strictly necessary, but it’s good practice.) Also, you can simplify some of the RESULT code and just do:

if ! eval "$CMD"; then
    echo "failed $CMD" >&2
    exit 1
fi

Note also that "failed $CMD" is almost certainly redundant, since you should get a decent error message from the command itself. It can be handy to see the full command that was executed, but generally shell scripts should not duplicate error messages that should be written by the tools they call. If you do write error messages, make sure they are written to stderr (hence the >&2 redirect).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading