BASH

Enforce Git Commit Message Format with a Hook

Implement a `commit-msg` Git hook in Bash to validate commit messages against a regex pattern, ensuring consistent, readable, and structured commit history.

#!/bin/bash
# This script should be placed in .git/hooks/commit-msg
# It checks if the commit message adheres to a specific format (e.g., "TYPE: Subject").

COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")

# Regex for "TYPE: Subject" where TYPE is e.g., feat, fix, docs, chore, style, refactor, test
# and Subject is not empty.
# Example: feat: Add new user authentication module
#          fix: Correct typo in README
COMMIT_REGEX="^(feat|fix|docs|chore|style|refactor|test): [A-Z].*"

if [[ ! "$COMMIT_MSG" =~ $COMMIT_REGEX ]]; then
    echo "--------------------------------------------------------"
    echo "ERROR: Invalid commit message format!"
    echo "Your commit message must follow the pattern: TYPE: Subject"
    echo "  TYPE can be: feat, fix, docs, chore, style, refactor, test"
    echo "  Subject must start with a capital letter."
    echo "Example: feat: Implement user login feature"
    echo "--------------------------------------------------------"
    exit 1
fi

exit 0
How it works: This Bash script acts as a `commit-msg` Git hook, which runs automatically every time a developer attempts to commit. It reads the commit message and validates it against a predefined regular expression. If the message does not conform to the specified format (e.g., `TYPE: Subject`), the script aborts the commit and displays an informative error message. This helps enforce coding standards, maintain a clean and searchable commit history, and improve team collaboration by ensuring all commit messages are consistent and descriptive.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs