CodeBlanks Logo Icon CodeBlanks

pre-commit

Learn pre-commit checks with the pre-commit hook.

What Is the pre-commit Hook?

The pre-commit hook runs immediately before Git creates a commit. You can perform checks such as code formatting, whitespace validation, and basic verification at this stage. If the hook exits with a failure status, Git stops the commit operation.

#!/bin/sh
# Check before commit
if [ -f "ERROR.txt" ]; then
    echo "Validation failed"
    exit 1
fi

Validation and Exit Status

A hook script usually returns 0 when successful and a nonzero exit code when it fails. The exit 1 command tells Git that the check was unsuccessful. This lets you prevent a commit when a required validation does not pass.

#!/bin/sh
if [ ! -f "README.md" ]; then
    echo "README is missing"
    exit 1
fi
exit 0

This check stops the commit when the README file is missing.

Practice Check a File Before Committing

Create a pre-commit script. If README.md does not exist, print an error message and terminate with exit 1. If the file exists, use exit 0.

Starter code

terminal
# README dosyasını kontrol et

# Eksikse hata döndür

# Varsa başarılı çık

Sample solution

terminal
if [ ! -f "README.md" ]; then
    echo "README.md eksik"
    exit 1
fi
exit 0

Expected output

README.md eksik

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 At which stage does the pre-commit hook run?

  • After a push to the remote repository is completed
  • When the repository is cloned for the first time
  • Before a commit is created Correct answer
  • After a commit has been successfully created

Explanation: pre-commit is triggered before the commit is created and can prevent the operation if it fails.

2 Report a Failed Check

Question
#!/bin/sh
____
Answer
#!/bin/sh
exit 1

Explanation: <code>exit 1</code> terminates the script with a failure status and prevents the commit operation.

3 pre-commit Components

Term Meaning
pre-commit Runs before a commit
exit 0 Successful exit
exit 1 Failure exit
README kontrolü Validates a required file

All lessons in Advanced