Git远程仓库post-commit钩子未触发问题排查求助
Let’s break down the most likely issues here, starting with the biggest misunderstanding that trips up a lot of folks:
1. You’re Using the Wrong Hook Type for Remote Pushes
The post-commit hook is a local repository hook — it only runs when you execute git commit on your local machine, not when code is pushed to a remote repository.
When you push code to a remote repo, the hook that triggers after the remote receives the commit is post-receive, not post-commit. This is almost certainly the root cause here. You’ll need to move your Jenkins trigger script into a post-receive file in the remote repo’s git/ProjectName/hooks directory, making sure it has the same executable permissions and git user ownership as your original post-commit file.
2. Double-Check the Hook’s Location and Naming
Git is strict about hook details:
- The hook must live in the
.git/hooksdirectory of the remote repository (not a top-levelhooksfolder in your project root). Confirm your path is actuallygit/ProjectName/.git/hooks/— it’s easy to miss the.gitsubfolder. - The file must have no extension — Git ignores files like
post-receive.shin the hooks directory. - Ensure the filename is spelled exactly (case-sensitive on most Unix-like systems):
post-receive(notPost-Receiveorpostreceive).
3. Re-Verify Permissions and Ownership
You mentioned the file is executable and owned by git, but let’s confirm with these commands (run as the git user on the remote server):
ls -l git/ProjectName/.git/hooks/post-receive
You should see permissions like -rwxr-xr-x (the first three bits are rwx for the owner). If not, fix it with:
chmod +x git/ProjectName/.git/hooks/post-receive chown git:git git/ProjectName/.git/hooks/post-receive
4. Environment Variable Mismatches
When you run the script manually as git, you’re using your interactive shell’s full environment. But Git runs hooks in a stripped-down, minimal context. Common issues here:
- The path to Jenkins CLI or
curl(whichever you use to trigger builds) isn’t in Git’sPATH. Hardcode the full path in your script (e.g.,/usr/bin/curlinstead of justcurl). - Missing authentication variables (like Jenkins API tokens stored in your shell profile). Add these directly to the script, or source your profile at the start:
source ~/.bash_profile
5. Test if the Hook Actually Runs
To confirm if the hook is firing at all, add a simple logging line at the top of your post-receive script:
echo "post-receive hook triggered at $(date)" >> /tmp/git_hook_debug.log
Push code again, then check /tmp/git_hook_debug.log. If the line appears, the hook is running, and the issue lies with your Jenkins trigger logic (not the hook itself).
内容的提问来源于stack exchange,提问作者Mike Balthasar

