【发布时间】:2015-11-28 03:45:39
【问题描述】:
我正在编写一个 git pre-commit 挂钩来检查是否有任何暂存文件包含不允许的文本,如果是这种情况则中止。
不是这方面的专家。到目前为止,我已经得到了这个
git diff --cached --name-status | while read x file; do
if [ "$x" == 'D' ]; then continue; fi
if [[ egrep "DISALLOWED_TEXT" ${file}]]; then
echo "ERROR: Disallowed text in file: ${file}"
exit 1
fi
done
似乎不起作用。我在提交时遇到了这些错误:
.git/hooks/pre-commit: line 16: conditional binary operator expected
.git/hooks/pre-commit: line 16: syntax error near `"DISALLOWED_TEXT"'
.git/hooks/pre-commit: line 16: ` if [[ egrep "DISALLOWED_TEXT" ${file}]]; then'
任何建议、想法和帮助表示赞赏。 谢谢!
已解决:(语法错误和功能失调的退出调用)
disallowed="word1 word2"
git diff --cached --name-status | while read x file; do
if [ "$x" == 'D' ]; then continue; fi
for word in $disallowed
do
if egrep $word $file ; then
echo "ERROR: Disallowed expression \"${word}\" in file: ${file}"
exit 1
fi
done
done || exit $?
【问题讨论】:
-
你错过了
${file}和]]之间的空格,如果你想使用@ 的返回状态,你实际上并不希望egrep调用周围的[[或]]987654329@ 作为if语句中的测试。 -
感谢您的关注。现在的另一个问题是发现错误后提交过程没有中止。
-
您看到错误输出并且
exit正在工作,但提交没有失败?看起来应该可以工作(|| exit $?可能没有必要)。 -
AFAIU,第一个出口是从子外壳调用的,因为它在一个循环中。因此,必须使用 $? 调用第二个出口以使用最新的返回值中止。指令。
-
while 正在一个子 shell 中运行,但它位于管道的右侧,所以当它退出时,没有任何东西在运行。试试看:
printf %s\\n a b c | while IFS= read -r line; do echo "$line"; exit 5; done; echo $?
标签: git bash shell unix git-bash