Git 预提交钩子(Hook)在文件中查找文本

标签 git bash shell unix git-bash

我正在编写一个 git 预提交 Hook 来检查是否有任何暂存文件包含不允许的文本,如果是这种情况则中止。

不是这方面的专家。到目前为止我已经得到了这个

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 $?

最佳答案

将此问题标记为有答案的答案:

OP 结束于:

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 $?

关于Git 预提交钩子(Hook)在文件中查找文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32356457/

相关文章:

bash - 从图像为 FFmpeg 生成调色板

bash - 使用 s3cmd 并行上传文件到 s3

linux - 为什么 bash 不会因短路命令序列中的错误而停止?

git - 使用带有 `git show` 的自定义差异工具

git - Github 贡献图中未显示进度?

git 子树推送和拆分添加 "-n<newline>"以提交消息

linux - 替换 sad "z"- 行解析

php - 如何在开发人员之间使用具有不同数据库配置的 Git?

linux - 使来自子进程的 shell 命令在父进程中执行(以锁定 shell)

linux - awk 第一列中的项目,然后再次 awk 使用第二列中的结果?