---
title: "Trusting a Git pre-commit hook to Run Checks Automatically"
description: "If you’re looking for a way to level up your automation skills, learn how Git pre-commit hooks automate Git actions in this step-by-step tutorial!"
canonical: "https://adamtheautomator.com/git-pre-commit-hook/"
---

# Trusting a Git pre-commit hook to Run Checks Automatically

> If you’re looking for a way to level up your automation skills, learn how Git pre-commit hooks automate Git actions in this step-by-step tutorial!

Source: https://adamtheautomator.com/git-pre-commit-hook/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Trusting a Git pre-commit hook to Run Checks Automatically](https://adamtheautomator.com/wp-content/uploads/2021/07/Automating-Client-Side-Git-Actions-with-Git-Hooks.jpg)

# Trusting a Git pre-commit hook to Run Checks Automatically

[![](https://secure.gravatar.com/avatar/5989a502f0009a732739a0b9015d53ea609ead5436ee9de6e7e662a34534bacd?s=192&d=mm&r=g)Chris Blackden](https://adamtheautomator.com/author/chris/)29 July 20216 min. read

Categories: [DevOps](/category/devops/)

Tags:[Git](/tag/git/)[Python](/tag/python/)

Table of Contents

*   [Prerequisites](#h-prerequisites)
*   [Learning How Git Commit and Git Hook Works](#h-learning-how-git-commit-and-git-hook-works)
*   [Correcting Badly Formatted Code via Black Code Formatter](#h-correcting-badly-formatted-code-via-black-code-formatter)
*   [Sharing Personal Pre-Commit Hooks with the Pre-Commit Framework](#h-sharing-personal-pre-commit-hooks-with-the-pre-commit-framework)
*   [Conclusion](#h-conclusion)

Forgetting to run checks before committing codes or scripts to run can be troublesome. But what if you can create a script that would run automatically to prevent disaster even before it happens? Running a Git pre-commit hook will save you from that disaster.

In this tutorial, you’ll learn how to make sure you wouldn’t miss even a semi-colon and run an entire unit testing suite. So, let’s start rolling!

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

*   A macOS, Linux, or Windows device. Demonstrations on this tutorial are on Ubuntu 20.04 running on WSL.
*   A Git local repository.
*   The [Git command-line](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) tool.
*   Python 3.8 with [pip](https://pip.pypa.io/en/stable/installing/) installed on your device. This tutorial uses Python, but you can write hook scripts for [Golang](https://go.dev/), [Javascript](https://www.javascript.com/), or even [HCL](https://github.com/hashicorp/hcl).

## Learning How Git Commit and Git Hook Works

Before you jump to automating Git Actions with Git hooks, it’s worth doing a quick review of what `git commit` is and how it works. The `git commit` command captures a snapshot of the changes you staged for a project, along with a message describing the changes.

When you run `git commit`, Git creates an object in memory with all of the information about the files added to the commit. That information includes the timestamp, author, and line-by-line file changes. A hash of these changes is generated to identify the change uniquely, then is saved to the object in memory.

After that object in memory is created, Git then reads the commit message or prompts the user to enter a commit message. The object and message are then saved to the filesystem under the _~/.git_ folder. You’ll know more about the _~/.git_ folder later.

Below is a diagram to help you better understand the step-by-step `git commit` process flow.

![Process flow diagram of git-commit](https://adamtheautomator.com/wp-content/uploads/2021/07/Untitled_Diagram.jpg)

Process flow diagram of `git-commit`

For each step of the `git commit` process, a Git hook is called. Git hooks are scripts that automatically run to change or alter steps in the `git commit` process before anything gets saved to the filesystem.

> _Git hooks aren’t meant to replace continuous integration and deployment pipelines. But they help catch any changes that would break those pipelines before they leave your local machine._

What’s great about Git hook scripts is that you can write the script in any scripting language that doesn’t need compiling, like Python or Ruby.

When you run `git commit`, there are three hooks that Git calls one after another:

*   The _pre-commit_ hook gets called first before any memory is used for the commit object.
*   The _prepare-commit-msg_ hook gets called when Git checks for the existence of a commit message.
*   The _commit-msg_ hook gets called after Git has received a commit message

Each hook has its own use cases, but for simplicity, the only one covered in this tutorial is the _pre-commit_ hook. You can see in the diagram below where each hook is triggered in the commit process.

![Showing where each hook is called during the git commit process](https://adamtheautomator.com/wp-content/uploads/2021/07/Untitled_Diagram-1.jpg)

Showing where each hook is called during the `git commit` process

## Correcting Badly Formatted Code via Black Code Formatter

Perhaps you’re looking for a way to correct a code’s format automatically. Ensuring that code looks a certain way may be important if you’re on a team. In this example, you’re going to invoke the [black](https://github.com/psf/black) code formatted utility automatically when you initiate a `git commit`.

> _The black code formatter is a Python module, which automatically corrects your code to a much readable format—how cool is that!_

1\. Launch your terminal and run the `pip` package manager to install the `black` code formatter, as shown below.

```python
pip install black
```

2\. Next, create a simple Python script like the one below and save it as _~/hello.py._ You’ll notice that the `"Hello world!"` string is on a different line than the print command.

The code below is valid and will `print` the words `Hello World!`, but the `"Hello World!"` line should be on the same line as the parentheses.

```python
#!/usr/bin/python
print(
      "Hello World!"
)
```

3\. Now, create a Git hook Shell script named _pre-commit.sh_ by copying and pasting the code below to your script and save it under the _~/.git/hooks_ directory.

> _You do not save Git hook scripts to a remote Git repository. Git hook scripts are stored locally._

The script below executes the `black` code formatter in the working directory (`.`) to automatically reformat the script created in the previous step.

```python
#!/bin/bash
python3 -m black .
```

> _If you prefer to change the code format manually, add the `--check` flag like this: `python3 -m black . --check`. The `--check` flag aborts the commit process when the code you’re committing is in bad format._

4\. Stage and commit the _~/hello.py_ file by running the following commands.

```python
# Stage the hello.py file
git add hello.py
# Commit the hello.py file to the Git repository with a commit message (-m)
git commit -m "This is badly formatted code"
```

Since you created the Git hook named _pre-commit_ in the previous step, the black code formatter will automatically run and correct the code from the ~/_hello.py_ script.

![Committing the file (hello.py) to your Git repository ](https://adamtheautomator.com/wp-content/uploads/2021/07/formatted_orig.png)

Committing the file (_hello.py_) to your Git repository

> _If any dependencies change, or you have tests that need to reach out to a database that your device doesn’t have access to, the hooks won’t work as expected._

5\. To see the changes made by the `black` formatter, run the `bat` command below followed by the file’s name (`hello.py`).

```python
bat hello.py
```

> _The `bat` command comes from a [Git repository](https://github.com/sharkdp/bat), letting you view a file’s content on the terminal, but is not required. Running the `cat` command on Linux and macOS or the [`Get-Content`](https://adamtheautomator.com/powershell-get-content/) cmdlet in PowerShell will do the same thing, but not as fancy._

Related:[Get-Content: Reading Text Files like a Boss in PowerShell](https://adamtheautomator.com/powershell-get-content/)

Below, you can see that the code from the _hello.py_ file is now in a much readable code format.

![Reformatted Code via black module](https://adamtheautomator.com/wp-content/uploads/2021/07/print.png)

Reformatted Code via `black` module

You’ve now seen how to execute a Git hook automatically before you perform a commit using the `black` formatter. If you plan to follow along with the rest of this tutorial, restore (`git restore`) the committed version of the `hello.py` file with the following command.

You’ll need an example of a badly formatted script for the following sections.

```python
git restore hello.py
```

## Sharing Personal Pre-Commit Hooks with the Pre-Commit Framework

> _To manage hooks at scale, use a purpose-built tool like the [pre-commit framework](https://pre-commit.com/) instead._

If you’re on a team and have now seen how beneficial a Git pre-commit hook can be, you might be wondering how to share Git hooks with other people. In that case, you may want to leverage the pre-commit framework. The pre-commit framework is a multi-language package manager, letting you save Git hooks to [version control](https://www.atlassian.com/git/tutorials/what-is-version-control).

With the pre-commit framework, your team or anyone else who clones your Git repository gets to use your Git hooks! Let’s cover a quick demonstration and see how the pre-commit framework works. For this demonstration, you’re installing hooks from the black code formatter’s repository.

1\. First, install the pre-commit framework on your local machine and check the installed version by running the following commands.

```bash
#!/bin/bash
# Downloads and runs the installation script (install-local.py) 
# from the https://pre-commit.com website
curl https://pre-commit.com/install-local.py | python3 - 

# Verify the pre-commit framework version installed
pre-commit --version
```

2\. Next, add a configuration file to reach out to the [black code formatter’s repository on GitHub](https://github.com/psf/black). To do so, create a new file called _.pre-commit-config.yaml_ in your text editor, then copy and paste the below configuration.

Below, the configuration tells the pre-commit framework to look in the `psf/black` repository on GitHub for the pre-commit hook.

```yaml
repos:
-   repo: https://github.com/psf/black
    rev: 21.6b0
    hooks:
    -   id: black
```

3\. Run the `pre-commit` command below to set up (`install`) the hooks defined in step two in your local _~/.git/hooks_ directory.

```python
pre-commit install
```

4\. Finally, stage the _~/hello.py_ file and run `git commit`. The outcome should be the same as the script earlier, except you’ll see the hook id (**black**), as shown below.

```bash
# Stage the hello.py file
git add hello.py
# Commit the hello.py file to the Git repository with a commit message (-m)
git commit -m "Using the pre-commit framework"
```

![Using the pre-commit framework to run the black formatter hook.](https://adamtheautomator.com/wp-content/uploads/2021/07/hookID.png)

Using the pre-commit framework to run the black formatter hook.

## Conclusion

Throughout this tutorial, you’ve learned how to create Git hooks locally and via the pre-commit framework to automate Git actions. You’ve also learned how Git hooks can increase code quality on your repository.

Now, go nuts and kick your automation skills up a notch by adding Git hooks to your projects or contributing to other projects!

Related:[Contributing to GitHub Projects (Git Pull Requests for Dummies)](https://adamtheautomator.com/git-pull-request/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fgit-pre-commit-hook%2F&text=Trusting%20a%20Git%20pre-commit%20hook%20to%20Run%20Checks%20Automatically)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fgit-pre-commit-hook%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fgit-pre-commit-hook%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2025/11/55418e927e511ae263219c072e27d637c2a967a5036de7020b329582db775c26.png)

### [Automating Docker Container Health Checks with Python and Local Notifications](/docker-health-checks-python/)

Docker's built-in health checks are passive—they tell Docker when a container fails, but do they tell you? In this tutorial, we'll build a lightweight Python monitoring system that runs entirely on your infrastructure with zero external dependencies. You'll learn to detect container failures in real-time, send instant alerts, and maintain a complete audit log of every state change.

![](https://adamtheautomator.com/wp-content/uploads/2024/01/gitops.jpg)

### [A Getting Started Guide to GitOps](/gitops/)

Embark on your GitOps journey—seamless, automated, and efficient. Explore the power of GitOps for streamlined workflows in this tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2021/12/How-To-Combine-Branches-With-Git-Merge.jpg)

### [Git Merge Simplified: Merging Branches Like a Pro](/git-merge/)

Master Git merge with this tutorial: Learn seamless branch combination techniques and best practices to enhance your development workflow, avoiding common errors.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
