0
0
Gitdevops~30 mins

pre-commit hook in Git - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a Git Pre-commit Hook to Check Commit Messages
📖 Scenario: You are working on a team project using Git. Your team wants to make sure every commit message starts with a capital letter and is at least 10 characters long. To help everyone follow this rule automatically, you will create a Git pre-commit hook script.
🎯 Goal: Build a Git pre-commit hook script that checks the commit message before the commit is saved. If the message does not start with a capital letter or is shorter than 10 characters, the commit will be stopped with a clear message.
📋 What You'll Learn
Create a pre-commit hook script file in the .git/hooks directory
Add a configuration variable to set the minimum commit message length
Write the core logic to check the commit message format
Print a message to allow or block the commit based on the check
💡 Why This Matters
🌍 Real World
Teams use pre-commit hooks to enforce commit message standards automatically, improving code history clarity.
💼 Career
Knowing how to write Git hooks is useful for DevOps engineers and developers to automate quality checks in version control.
Progress0 / 4 steps
1
Create the pre-commit hook script file
Create a file called .git/hooks/pre-commit and add the first line #!/bin/sh to specify the shell interpreter.
Git
Need a hint?

The first line of a shell script should be #!/bin/sh to tell Git how to run it.

2
Add a minimum length configuration variable
Inside the pre-commit script, create a variable called MIN_LENGTH and set it to 10 to define the minimum commit message length.
Git
Need a hint?

Use MIN_LENGTH=10 to store the minimum length number.

3
Write the logic to check the commit message
Add code to read the commit message from .git/COMMIT_EDITMSG into a variable called MSG. Then check if the first character is uppercase and if the message length is at least $MIN_LENGTH. If either check fails, print Commit message invalid and exit with status 1 to block the commit.
Git
Need a hint?

Use head -n1 .git/COMMIT_EDITMSG to get the first line of the commit message. Use shell string length and grep to check conditions.

4
Print success message if commit message is valid
At the end of the script, add a line to print Commit message valid and exit with status 0 to allow the commit.
Git
Need a hint?

Use echo to print the success message and exit 0 to allow the commit.