---
title: Using git's pre-commit hook
url: https://calvin.my/posts/using-git-s-pre-commit-hook
published: 2025-07-04
updated: 2026-09-16
category: Development
tags:
- git
- Ruby
summary: The post explains how a Git pre-commit hook can enforce code quality and security checks before changes are committed. It outlines placing an executable hook in the repository’s hooks directory, then running RuboCop for linting and Brakeman for vulnerability detection. Commits proceed only when both checks pass, while developers can bypass the hook when necessary using Git’s verification-skip option.
---

# Using git's pre-commit hook

Git hooks are triggered when important events occur, such as before a commit is executed or after a commit is completed. They are designed to introduce custom workflows by running a script when the hook is triggered.

In this article, we use the pre-commit hook to perform a linter check and a vulnerability check. The commit is only allowed if both checks are successful.

* * *

## Setup

1. Navigate into `.git/hooks` directory.
2. Create a new script file and name it&nbsp;`pre-commit`.
3. Make it executable with `chmod +x`.

* * *

## Implementation

In this script file, we want to run two commands: Brakeman and Rubocop, to check our application code.

```bash
#!/bin/bash

set -e

echo "Running pre-commit checks..."

echo "Running RuboCop..."
if ! bundle exec rubocop; then
  echo "RuboCop failed. Please fix the issues and try again."
  exit 1
fi

echo "Running Brakeman..."
if ! bundle exec brakeman -q; then
  echo "Brakeman found security issues. Please fix them and try again."
  exit 1
fi

echo "All checks passed!"
```

* * *

## Testing

1. We modify some code to fail the Rubocop test.
2. Then we try to commit the updated code.

   ```bash
   $  git commit -m "Test"
   ```

   ![](https://camy-pub.s3.ap-southeast-1.amazonaws.com/cc7e07ae-d0c4-41dc-9fca-482f9e666774.png)

* * *

## Escape

Use the `no-verify` command to skip the script result.

```bash
$git commit -m "Message" --no-verify
```
