0
0
Gitdevops~15 mins

commit-msg hook for message validation in Git - Mini Project: Build & Apply

Choose your learning style9 modes available
commit-msg hook for message validation
📖 Scenario: You are working on a team project where every commit message must start with a ticket number like PROJ-123 followed by a short description. This helps everyone understand what the commit is about and links it to the right task.
🎯 Goal: Create a commit-msg Git hook script that checks if the commit message starts with a ticket number pattern PROJ- followed by digits. If the message does not match, the commit should be rejected with a clear error message.
📋 What You'll Learn
Create a commit-msg hook script file
Check the commit message file content for the pattern PROJ- followed by digits at the start
Reject the commit if the pattern is missing with a message
Allow the commit if the pattern is present
💡 Why This Matters
🌍 Real World
Teams use commit-msg hooks to enforce commit message standards, improving project tracking and collaboration.
💼 Career
Knowing how to write Git hooks is useful for DevOps roles and software developers to maintain code quality and workflow consistency.
Progress0 / 4 steps
1
Create the commit-msg hook script file
Create a file named commit-msg inside the .git/hooks/ directory with 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 which shell to use.

2
Read the commit message from the file
Add a line to read the commit message from the file path passed as the first argument $1 into a variable named commit_msg.
Git
Need a hint?

Use commit_msg=$(cat "$1") to read the commit message content.

3
Check if commit message starts with 'PROJ-' followed by digits
Add an if statement that uses grep -qE to check if commit_msg starts with the pattern PROJ- followed by one or more digits. If it does not match, print Error: Commit message must start with PROJ- followed by ticket number. and exit with status 1.
Git
Need a hint?

Use grep -qE '^PROJ-[0-9]+' to check the pattern at the start of the message.

4
Allow commit if message is valid
Add a line to exit with status 0 at the end of the script to allow the commit if the message passed the check.
Git
Need a hint?

Use exit 0 to indicate success and allow the commit.