如果 git 命令失败,如何退出 git 挂钩脚本?

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

我有一个 post-receive git 钩子:

#!/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

如何检查 git 命令的状态并在失败时停止脚本继续?

类似于以下内容:

#!/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

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

检查任何 shell 命令状态的方法相同:通过查看 return 代码。您可以在命令退出后检查 shell 变量 $? 的值,如:

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

或者通过使用命令本身作为条件的一部分,如:

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