Bird
Raised Fist0
Gitdevops~10 mins

pre-commit hook in Git - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - pre-commit hook
Make code changes
↓
Run 'git commit'
↓
Git triggers pre-commit hook script
↓
Hook script runs checks
↓
Commit
↓
Fix issues and retry
When you run 'git commit', Git runs the pre-commit hook script first. If the script passes, the commit happens. If it fails, the commit stops so you can fix problems.
Execution Sample
Git
#!/bin/sh
# pre-commit hook example

# Check for TODO comments
if git diff --cached | grep -q 'TODO'; then
  echo 'Error: TODO found in staged files.'
  exit 1
fi
exit 0
This pre-commit hook checks if any staged files contain 'TODO'. If yes, it stops the commit with an error.
Process Table
StepActionCommand/CheckResultNext Step
1User runs 'git commit'git commitTriggers pre-commit hookRun hook script
2Hook script runs checkgit diff --cached | grep 'TODO'No TODO foundAllow commit
3Commit proceedsgit commit completesCommit savedEnd
4User runs 'git commit' againgit commitTriggers pre-commit hookRun hook script
5Hook script runs checkgit diff --cached | grep 'TODO'TODO foundAbort commit
6Commit abortedexit 1Commit stoppedUser fixes TODO and retries
💡 Commit stops if TODO found; otherwise commit completes.
Status Tracker
VariableStartAfter Step 2After Step 5Final
TODO_foundundefinedfalsetruetrue
Commit_statusnot startedallowedabortedaborted or completed
Key Moments - 3 Insights
Why does the commit stop even though I typed 'git commit'?
The pre-commit hook script found a TODO in staged files (see execution_table step 5), so it exited with error to prevent committing unfinished code.
What happens if the pre-commit hook script passes all checks?
If no problems are found (execution_table step 2), the commit proceeds normally (step 3) and your changes are saved.
How can I fix a failed pre-commit hook?
Fix the issues reported by the hook (like removing TODO comments), stage the changes again, and run 'git commit' to retry (see execution_table step 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of the hook check at step 2?
ATODO found, commit aborted
BNo TODO found, commit allowed
CHook script did not run
DCommit completed
💡 Hint
Check the 'Result' column at step 2 in the execution_table.
At which step does the commit get aborted due to a failed hook?
AStep 3
BStep 1
CStep 5
DStep 6
💡 Hint
Look for 'TODO found' and 'Abort commit' in the execution_table.
If the hook script always exits with 0, what will happen to the commit?
ACommit will always proceed
BHook script will not run
CCommit will always be aborted
DGit will show an error
💡 Hint
Refer to the exit codes in the execution_table and how they affect commit status.
Concept Snapshot
pre-commit hook is a script Git runs before saving a commit.
It can check code or files and stop commit if problems found.
Place script in .git/hooks/pre-commit and make executable.
Exit 0 means pass; exit non-zero means fail and abort commit.
Useful to enforce code quality automatically.
Full Transcript
When you run 'git commit', Git first runs the pre-commit hook script if it exists. This script can check your staged files for issues like TODO comments. If the script finds a problem, it exits with an error code, stopping the commit so you can fix it. If no problems are found, the commit proceeds normally. This helps keep your code clean by preventing commits with unfinished or problematic code. You can create a pre-commit hook by adding an executable script named 'pre-commit' in the .git/hooks directory. The script should exit with 0 to allow commit or non-zero to stop it.

Practice

(1/5)
1. What is the main purpose of a pre-commit hook in Git?
easy
A. To push commits to the remote repository automatically
B. To run scripts before a commit is saved to catch errors early
C. To delete files from the repository before committing
D. To automatically merge branches after a commit

Solution

  1. Step 1: Understand what pre-commit hooks do

    Pre-commit hooks run scripts before a commit is finalized to check code or enforce rules.
  2. Step 2: Identify the correct purpose

    They help catch errors early by running checks before saving changes.
  3. Final Answer:

    To run scripts before a commit is saved to catch errors early -> Option B
  4. Quick Check:

    Pre-commit hook purpose = run scripts before commit [OK]
Hint: Pre-commit hooks run before saving commits to catch issues [OK]
Common Mistakes:
  • Confusing pre-commit with post-commit hooks
  • Thinking hooks automatically push commits
  • Believing hooks delete files automatically
2. Which of the following is the correct way to make a pre-commit hook script executable on Linux?
easy
A. chmod +x .git/hooks/pre-commit
B. git enable pre-commit
C. chmod 000 .git/hooks/pre-commit
D. git hook run pre-commit

Solution

  1. Step 1: Identify how to make scripts executable

    On Linux, chmod +x sets execute permission on a file.
  2. Step 2: Apply to pre-commit hook script

    Running chmod +x .git/hooks/pre-commit makes the hook script executable so Git can run it.
  3. Final Answer:

    chmod +x .git/hooks/pre-commit -> Option A
  4. Quick Check:

    Make hook executable = chmod +x [OK]
Hint: Use chmod +x to make hook scripts executable [OK]
Common Mistakes:
  • Using git commands instead of chmod for permissions
  • Setting permissions to 000 disables execution
  • Assuming hooks run without executable permission
3. Given this pre-commit hook script content:
#!/bin/sh
if git diff --cached --name-only | grep -q '\.py$'; then
  echo 'Python files changed'
else
  echo 'No Python files changed'
fi

What will be the output if you commit a changed file named app.js?
medium
A. No Python files changed
B. Python files changed
C. Syntax error in script
D. Hook will not run

Solution

  1. Step 1: Understand the script logic

    The script checks staged files for names ending with '.py'. If found, it prints 'Python files changed'. Otherwise, it prints 'No Python files changed'.
  2. Step 2: Apply to the committed file

    The committed file is 'app.js', which does not end with '.py', so the else branch runs.
  3. Final Answer:

    No Python files changed -> Option A
  4. Quick Check:

    File extension check = no match = else output [OK]
Hint: Check file extensions in staged files to predict output [OK]
Common Mistakes:
  • Assuming any changed file triggers 'Python files changed'
  • Confusing staged vs unstaged files
  • Ignoring the file extension check
4. You wrote a pre-commit hook script but it does not run when committing. Which of these is the most likely cause?
medium
A. The script is placed outside the .git/hooks directory
B. The script is named pre-commit.sh instead of pre-commit
C. All of the above
D. The script is not executable

Solution

  1. Step 1: Check script permissions

    If the script is not executable, Git cannot run it.
  2. Step 2: Check script name and location

    The script must be named exactly 'pre-commit' and placed inside the '.git/hooks' folder to be recognized.
  3. Step 3: Combine all issues

    Any of these problems will prevent the hook from running, so all are valid causes.
  4. Final Answer:

    All of the above -> Option C
  5. Quick Check:

    Hook runs only if name, location, and permissions are correct [OK]
Hint: Check name, location, and execute permission for hooks [OK]
Common Mistakes:
  • Ignoring file permissions
  • Naming script with extensions like .sh
  • Placing script outside .git/hooks folder
5. You want a pre-commit hook that prevents commits if any staged file contains the word 'TODO'. Which script snippet correctly implements this?
hard
A. #!/bin/sh git commit -m 'Check TODOs' || exit 1
B. #!/bin/sh grep -r 'TODO' . && echo 'TODO found' && exit 1
C. #!/bin/sh git status | grep 'TODO' && exit 1
D. #!/bin/sh git diff --cached | grep -q 'TODO' && echo 'Remove TODOs before commit' && exit 1

Solution

  1. Step 1: Understand the goal

    The hook must check staged changes for the word 'TODO' and stop commit if found.
  2. Step 2: Analyze each option

    #!/bin/sh git diff --cached | grep -q 'TODO' && echo 'Remove TODOs before commit' && exit 1 uses git diff --cached to check staged changes and exits with error if 'TODO' is found, which is correct.
    #!/bin/sh grep -r 'TODO' . && echo 'TODO found' && exit 1 searches all files recursively, not just staged changes.
    #!/bin/sh git commit -m 'Check TODOs' || exit 1 tries to run a commit inside the hook, which is incorrect.
    #!/bin/sh git status | grep 'TODO' && exit 1 checks git status output, which does not show file contents.
  3. Final Answer:

    #!/bin/sh git diff --cached | grep -q 'TODO' && echo 'Remove TODOs before commit' && exit 1 -> Option D
  4. Quick Check:

    Check staged diff for TODO and exit if found [OK]
Hint: Use git diff --cached to scan staged changes for keywords [OK]
Common Mistakes:
  • Searching unstaged files instead of staged
  • Running git commit inside hook
  • Checking git status output for content
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard