Skip to content

Instantly share code, notes, and snippets.

@codeinthehole
Last active November 3, 2025 10:41
Show Gist options
  • Save codeinthehole/ab6ba6d20647e805dc83f9e22aeb2620 to your computer and use it in GitHub Desktop.
Save codeinthehole/ab6ba6d20647e805dc83f9e22aeb2620 to your computer and use it in GitHub Desktop.
Bash script to run pre-commit on every commit in a PR branch
#!/usr/bin/env bash
# Run pre-commit on every commit in your PR branch.
#
# The rebase will stop is pre-commit fails on any commit, allowing you to fix
# the issues. Once you've made changes, verify that pre-commit now passes on
# that commit with:
#
# pre-commit run --from HEAD^ --to HEAD
#
# See https://til.codeinthehole.com/posts/how-to-run-precommit-using-an-interactive-rebase/
set -eo pipefail
function main() {
# Define the pre-commit command to run. We can choose to either run the hooks on just
# the commit diff or on the whole repo after each commit (slower but more thorough).
# Run hooks on commit diff.
# precommit_cmd="pre-commit run --hook-stage commit --from HEAD^ --to=HEAD"
# Run hooks on whole repo.
precommit_cmd="pre-commit run --hook-stage commit --all-files"
# To make the output easier to read, we print commit information before running the
# pre-commit command.
cmd="git show --name-only; echo; $precommit_cmd"
git rebase --exec "$cmd" "$(rebase_ref)"
}
# Return the Git ref to start the rebase from.
function rebase_ref() {
# Look for the merge-base between the current branch and the default branch.
#
# `defaultbranch` is a custom alias that returns the default branch name.
# defaultbranch = "!f() { git symbolic-ref refs/remotes/origin/HEAD | cut -d/ -f4; }; f"
git merge-base origin/"$(git defaultbranch)" HEAD
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment