condition总是返回false

时间:2016-05-17 13:07:59

标签: bash shell githooks

以下是我的预提交git hoook

#!/bin/bash

....
# if git diff -U0 "$FILE_PATH" | grep -iq 'todo'; # Double quoting $FILE_PATH doesnt' change anything
if git diff -U0 $FILE_PATH | grep -iq 'todo';
then
    echo $FILE_PATH ' -> Contains TODO'
    exit 1

else
    echo 'nooooooooooooooooooooooooooooooooooo'
fi

我总是收到noooooooooooooooooooo消息,但是下面的命令直接在我的终端上尝试,效果很好:

git diff -U0 my/file/path.php | grep -iq 'todo' && echo 'true' || echo 'false'

输出

true

更新

当运行bash .git/hooks/pre-commit时,它很有效,非常奇怪!

FYI

我不知道它是否是一个重要信息,但.git / hooks / pre-commit是一个符号链接

1 个答案:

答案 0 :(得分:1)

最有可能的是,您的管道不会返回状态0.要验证是否是这种情况(而不是您编写复合语句的方式),您可以将其重写为

git diff -U0 "$FILE_PATH" | grep -iq 'todo'
grep_status=$?
echo grep status is $grep_status
if (( grep_status == 0 ))
then
  echo contains todo
else
  echo no
fi

我还注意到您的代码在if行中包含不必要的分号。我首先想到这个分号可能会导致奇怪的行为,但至少在bash我尝试过你的代码时,它似乎没有任何伤害。不过,为了安全起见,我会删除它。

相关问题