2017-08-03 70 views
0

我有一个混帐post-receive钩:如果git命令失败,如何退出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 
+1

用'运行它/ bin/bash -e'(或者'set -e' =='set -o errexit'),并且shell会在未经检查的命令失败时自动为您执行。 – PSkocik

+0

@PSkocik'-e'通常因为其不直观的语义而受到阻碍。请参阅[为什么set -e不能在()||]内工作(https://unix.stackexchange.com/questions/65532/why-does-set-e-not-work-inside)。 – hvd

+0

@ hvd是的,这绝对是'set -e',但我仍然认为简单的shell脚本默认应该是'set -e'。太糟糕了,因为你提到的行为,在图书馆的shell函数中不能依赖它。 :( – PSkocik

回答

1

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

以同样的方式,你检查任何shell命令的状态:通过查看返回码。您可以在命令退出后检查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 
+1

这似乎是不必要的详细信息'|| exit 1'就足够了 – hvd

+0

如果你想发出某种有用的错误信息(OP在问题中做什么),那么不是。 – larsks

+0

而你不是如果你想发出一个有用的错误信息,我会使用'||',但是与shell函数一起使用:'|| fail“命令行失败,''与'fail(){echo“error:$ 1”>&2; exit 1;}'。当你稍后阅读脚本时,这不会分散注意力。 – hvd

相关问题