简体   繁体   English

如何在预提交钩子中使用 git diff 的退出代码

[英]How to use exit code of git diff in pre-commit hook

I have a project with a backend and a frontend, but since the git pre-commit hook gets executed for every change I need to check if the changes were made in the frontend.我有一个带有后端和前端的项目,但是由于每次更改都会执行 git pre-commit 挂钩,因此我需要检查是否在前端进行了更改。

I tried this pre-commit hook:我试过这个预提交钩子:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

git diff --cached --name-only --quiet frontend
if [ $? -eq 1 ]; then
  cd frontend && npm run lint
fi

But for some reason it fails when running the git command -- which works fine in my terminal.但是由于某种原因,它在运行 git 命令时失败了——这在我的终端中运行良好。 The error I get is:我得到的错误是:

husky - pre-commit hook exited with code 1 (error) husky - 预提交钩子以代码 1 退出(错误)

That does not really help.这并没有真正的帮助。 My guess is that the git command returns an error code and the script thus ends.我的猜测是 git 命令返回一个错误代码,脚本因此结束。

Any idea how to fix this?知道如何解决这个问题吗?

A shell script always exits with the exit code of the command which was executed last or with the code specified with the exit builtin. shell 脚本总是以最后执行的命令的退出代码或使用exit内置命令指定的代码exit

If you need your script to always exit with a specific exit code (eg always success, 0 ), make sure you explicitly specify the exit code:如果您需要脚本始终以特定退出代码退出(例如,始终成功, 0 ),请确保明确指定退出代码:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

git diff --cached --name-only --quiet frontend
if [ $? -eq 1 ]; then
  cd frontend && npm run lint
fi

exit 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM