0
0
Gitdevops~30 mins

Creating custom hook scripts in Git - Try It Yourself

Choose your learning style9 modes available
Creating Custom Git Hook Scripts
📖 Scenario: You are working on a team project using Git. Your team wants to ensure that every commit message includes the word "JIRA" followed by a ticket number. To help with this, you will create a custom Git hook script that checks commit messages before they are saved.
🎯 Goal: Build a Git commit-msg hook script that checks if the commit message contains the word "JIRA" followed by a ticket number. If the message does not match, the commit should be stopped with a clear message.
📋 What You'll Learn
Create a Git hook script file named commit-msg in the .git/hooks directory
Add a check in the script to verify the commit message contains the pattern JIRA- followed by digits
Make the script executable
Test the hook by attempting a commit with and without the required pattern
💡 Why This Matters
🌍 Real World
Teams often use Git hooks to enforce rules and automate checks before code changes are saved. This helps keep code quality high and consistent.
💼 Career
Knowing how to create and use Git hooks is valuable for developers and DevOps engineers to automate workflows and enforce team policies.
Progress0 / 4 steps
1
Create the Git 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
Add a variable to read the commit message file path
Add a line to the script that assigns the first argument $1 to a variable named commit_msg_file.
Git
Need a hint?

The commit message file path is passed as the first argument to the script. Save it in a variable for later use.

3
Add the check for the JIRA ticket pattern
Add an if statement that uses grep -qE to check if the commit message file contains the pattern JIRA-[0-9]+. If the pattern is not found, print Commit message must include a JIRA ticket like JIRA-123 and exit with status 1.
Git
Need a hint?

Use grep -qE 'JIRA-[0-9]+' to quietly check for the pattern. If not found, print a message and stop the commit with exit 1.

4
Make the script executable and test it
Run chmod +x .git/hooks/commit-msg to make the script executable. Then run git commit -m "Test commit without JIRA ticket" and observe the output.
Git
Need a hint?

Use chmod +x to make the script executable. When you try to commit without a JIRA ticket, the script should stop the commit and show the message.