Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

githooks

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
like image 562
Don P Avatar asked Feb 26 '26 08:02

Don P


1 Answers

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
like image 182
larsks Avatar answered Feb 27 '26 22:02

larsks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!