Don
Don

Reputation: 4202

How to exit a git hook script if a git command fails?

I have a post-receive git hook:

#!/bin/bash

while read oldrev newrev refname
do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    if [ -n "$branch" ] && [ "master" == "$branch" ]; then
       working_tree="/path/to/working/dir"
       GIT_WORK_TREE=$working_tree git checkout $branch -f
       GIT_WORK_TREE=$working_tree git pull
       <more instructions>
    fi
done

How can I check the status of a git command and stop the script from continuing if it fails?

Something like the following:

#!/bin/bash

while read oldrev newrev refname
do
    branch=$(git rev-parse --symbolic --abbrev-ref $refname)
    if [ -n "$branch" ] && [ "master" == "$branch" ]; then
       working_tree="/path/to/working/dir"
       GIT_WORK_TREE=$working_tree git checkout $branch -f
       GIT_WORK_TREE=$working_tree git pull
       if [ <error conditional> ]
           echo "error message"
           exit 1
       fi
    fi
done

Upvotes: 3

Views: 2842

Answers (1)

larsks
larsks

Reputation: 311713

How can I check the status of a git command and stop the script from continuing if it fails?

The same way you check the status of any shell command: by looking at the return code. You can inspect the value of the shell variable $? after the command exits, as in:

GIT_WORK_TREE=$working_tree git pull
if [ $? -ne 0 ]; then
  exit 1
fi

Or by using the command itself as part of a conditional, as in:

if ! GIT_WORK_TREE=$working_tree git pull; then
  exit 1
fi

Upvotes: 3

Related Questions