15 Git Automation Scripts to Save Time

15 Git automation scripts and hooks in Bash: prune merged branches, update many repos, check commit messages, block pushes to main, tag releases and more.

Dec 25, 2025 - 12:28
Nov 7, 2026 - 16:04
 0  135
15 Git Automation Scripts to Save Time

Git automation scripts save time by turning repeated terminal chores into one command or a hook that runs on its own: pruning merged branches, updating many repositories at once, validating commit messages, blocking pushes to main, tagging releases, and finding large files. The 15 scripts below use standard Git commands, Bash and Git hooks.

Each script is short enough to read in a minute, uses only commands documented on git-scm.com, and says where to put it. Test them on a throwaway clone first, especially anything that deletes branches. If you need a refresher on the commands themselves, start with 25 Git commands every DevOps engineer must know.

Key takeaways

  • Put personal helpers in ~/bin or as Git aliases. Any executable named git-something on your PATH runs as git something.
  • Share hooks with a team by committing them to a folder such as .githooks and running git config core.hooksPath .githooks. Client-side hooks are not copied by git clone.
  • Client hooks can be skipped with --no-verify, so enforce critical rules again in CI or with server-side branch protection.
  • Use plumbing commands such as git for-each-ref and git rev-list in scripts. Their output is stable, unlike porcelain output meant for humans.
  • Any script that deletes branches or rewrites history should default to a dry run.

The 15 scripts at a glance

#ScriptTypeSaves you from
1Prune merged local branchesBashScrolling through dozens of stale branches
2Delete merged remote branches (dry run first)BashCluttered remote branch lists
3Update every repo in a folderBashRunning pull in ten directories
4Branches sorted by last commitAliasForgetting what you worked on
5Commit message checkcommit-msg hookInconsistent history
6Block direct pushes to mainpre-push hookAccidental pushes
7Block secrets and large files at commitpre-commit hookLeaked keys and bloated repos
8Prefix commits with the ticket IDprepare-commit-msg hookTyping ticket numbers
9Sync a fork with upstreamBashRemembering remote names and steps
10Tag the next semantic versionBashManual version bumps
11Changelog from commitsBashHand-written release notes
12Find the largest objects in historyBashGuessing why a clone is slow
13Automated bisectBashTesting commits one by one
14Worktree per pull requestBashStashing to review a branch
15Background maintenance and reuse of conflict fixesOne-time configSlow repos and repeated conflicts

Setup: where scripts and hooks live

mkdir -p ~/bin
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc

# Team hooks, committed to the repository
mkdir -p .githooks
git config core.hooksPath .githooks
chmod +x .githooks/*

Every script below starts with set -euo pipefail so it stops on the first error instead of carrying on with bad data.

1. Prune merged local branches

Deletes local branches already merged into the main branch, skipping the current and protected branches.

#!/usr/bin/env bash
# ~/bin/git-prune-merged
set -euo pipefail
base="${1:-main}"
git fetch --prune --quiet
git branch --merged "$base" --format='%(refname:short)' \
  | grep -vE "^(${base}|main|master|develop)$" \
  | while read -r b; do
      [ "$b" = "$(git branch --show-current)" ] && continue
      git branch -d "$b"
    done

git branch -d refuses to delete unmerged work, which makes this safe. Run it as git prune-merged.

2. Delete merged remote branches, with a dry run

#!/usr/bin/env bash
# ~/bin/git-prune-remote  (pass --apply to actually delete)
set -euo pipefail
base="${BASE:-main}"
git fetch --prune origin
for ref in $(git branch -r --merged "origin/$base" --format='%(refname:short)'); do
  b="${ref#origin/}"
  case "$b" in "$base"|HEAD|origin|main|master|develop|release/*) continue ;; esac
  if [ "${1:-}" = "--apply" ]; then
    git push origin --delete "$b"
  else
    echo "would delete: $b"
  fi
done

Check with your team first. Many Git hosts can delete branches automatically after a merge request merges, which may make this unnecessary.

3. Update every repository in a folder

#!/usr/bin/env bash
# ~/bin/git-pull-all  usage: git pull-all ~/work
set -uo pipefail
root="${1:-.}"
for dir in "$root"/*/; do
  [ -d "$dir/.git" ] || continue
  echo "== $dir"
  if [ -n "$(git -C "$dir" status --porcelain)" ]; then
    echo "   skipped: uncommitted changes"
    continue
  fi
  git -C "$dir" pull --ff-only --quiet || echo "   pull failed"
done

git -C runs Git in another directory without cd. --ff-only refuses to create surprise merge commits.

4. List branches by most recent commit

git config --global alias.recent \
  "for-each-ref --sort=-committerdate refs/heads --count=15 \
   --format='%(committerdate:relative)%09%(refname:short)%09%(subject)'"

git recent

5. Validate commit messages (commit-msg hook)

Enforces a Conventional Commits style subject such as fix(api): handle empty token.

#!/usr/bin/env bash
# .githooks/commit-msg
set -euo pipefail
subject="$(head -n1 "$1")"
pattern='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9._-]+\))?!?: .{1,72}$'
if ! printf '%s' "$subject" | grep -qE "$pattern"; then
  echo "Commit subject does not match: type(scope): summary (max 72 chars)" >&2
  echo "Got: $subject" >&2
  exit 1
fi

Git passes the path of the message file as the first argument. A non-zero exit aborts the commit. For the reasoning behind message rules, see 12 best practices for Git commit messages.

6. Block direct pushes to main (pre-push hook)

#!/usr/bin/env bash
# .githooks/pre-push
set -euo pipefail
protected='^refs/heads/(main|master|release/.*)$'
while read -r local_ref local_sha remote_ref remote_sha; do
  if printf '%s' "$remote_ref" | grep -qE "$protected"; then
    echo "Direct push to $remote_ref is blocked. Open a pull request." >&2
    exit 1
  fi
done

The pre-push hook reads one line per ref on standard input, as documented in githooks(5). Back it up with branch protection rules on GitHub or GitLab, since --no-verify skips the hook.

7. Block secrets and large files (pre-commit hook)

#!/usr/bin/env bash
# .githooks/pre-commit
set -euo pipefail
max_kb=5120
fail=0
while IFS= read -r -d '' f; do
  [ -f "$f" ] || continue
  size_kb=$(( $(wc -c < "$f") / 1024 ))
  if [ "$size_kb" -gt "$max_kb" ]; then
    echo "Too large (${size_kb} KB): $f" >&2; fail=1
  fi
done < <(git diff --cached --name-only -z --diff-filter=ACM)

if git diff --cached -U0 | grep -qE 'AKIA[0-9A-Z]{16}|-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----'; then
  echo "Possible secret in staged changes." >&2; fail=1
fi
exit $fail

This catches the obvious cases. For real coverage, use a dedicated scanner such as gitleaks through the pre-commit framework, described in our guide to enforcing repo standards with pre-commit hooks, and read storing secrets in Git safely.

8. Add the ticket ID from the branch name (prepare-commit-msg hook)

#!/usr/bin/env bash
# .githooks/prepare-commit-msg
set -euo pipefail
msg_file="$1"; source="${2:-}"
[ -n "$source" ] && exit 0   # skip merges, amends, -m messages
branch="$(git branch --show-current)"
ticket="$(printf '%s' "$branch" | grep -oE '[A-Z]+-[0-9]+' | head -n1 || true)"
[ -z "$ticket" ] && exit 0
grep -q "$ticket" "$msg_file" || sed -i.bak "1s/^/$ticket: /" "$msg_file" && rm -f "$msg_file.bak"

On branch feature/OPS-142-retry, the editor opens with OPS-142: already filled in.

9. Sync a fork with upstream

#!/usr/bin/env bash
# ~/bin/git-sync-fork
set -euo pipefail
branch="${1:-main}"
git remote get-url upstream >/dev/null 2>&1 || { echo "add an 'upstream' remote first" >&2; exit 1; }
git fetch upstream
git switch "$branch"
git merge --ff-only "upstream/$branch"
git push origin "$branch"

10. Tag the next semantic version

#!/usr/bin/env bash
# ~/bin/git-bump  usage: git bump [major|minor|patch]
set -euo pipefail
part="${1:-patch}"
last="$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || echo v0.0.0)"
IFS=. read -r major minor patch <<< "${last#v}"
case "$part" in
  major) major=$((major+1)); minor=0; patch=0 ;;
  minor) minor=$((minor+1)); patch=0 ;;
  patch) patch=$((patch+1)) ;;
  *) echo "use major, minor or patch" >&2; exit 1 ;;
esac
next="v${major}.${minor}.${patch}"
git tag -a "$next" -m "Release $next"
echo "Created $next (push with: git push origin $next)"

Annotated tags (-a) store the tagger and date, and git describe looks for annotated tags by default.

11. Generate a changelog from commits

#!/usr/bin/env bash
# ~/bin/git-changelog
set -euo pipefail
from="${1:-$(git describe --tags --abbrev=0)}"
to="${2:-HEAD}"
echo "## Changes from $from to $to"
for type in feat fix perf; do
  lines="$(git log "$from..$to" --no-merges --pretty=format:'- %s (%h)' | grep -E "^- ${type}(\(|:)" || true)"
  [ -n "$lines" ] && printf '\n### %s\n%s\n' "$type" "$lines"
done

This works well with script 5, because consistent prefixes make commits easy to group.

12. Find the largest objects in history

#!/usr/bin/env bash
# ~/bin/git-big-objects
set -euo pipefail
git rev-list --objects --all \
  | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
  | awk '$1 == "blob"' \
  | sort -k3 -n -r \
  | head -n "${1:-20}" \
  | awk '{ printf "%8.1f MB  %s\n", $3/1048576, $4 }'

Removing a file in a new commit does not shrink history. To purge it you need a history rewrite tool such as git filter-repo, coordinated with everyone who has a clone. For a lasting fix, track large binaries with Git LFS. Our Git repository management practices cover this.

13. Find the commit that broke a test with git bisect run

#!/usr/bin/env bash
# ~/bin/git-find-break  usage: git find-break v1.4.0 "npm test"
set -euo pipefail
good="$1"; shift
git bisect start HEAD "$good"
git bisect run sh -c "$*"
git bisect reset

git bisect run treats exit code 0 as good, 125 as "skip this commit", and other codes from 1 to 127 as bad. It binary-searches history, so a thousand commits take about ten test runs.

14. Review a branch in its own worktree

#!/usr/bin/env bash
# ~/bin/git-review  usage: git review feature/login
set -euo pipefail
branch="$1"
dir="../review-${branch//\//-}"
git fetch origin "$branch"
git worktree add "$dir" "origin/$branch"
echo "Review in $dir, then remove with: git worktree remove $dir"

A worktree is a second working directory attached to the same repository, so you can test someone's branch without stashing your own changes.

15. One-time setup: background maintenance and rerere

# Schedule hourly prefetch, commit-graph and other upkeep for this repo
git maintenance start

# Remember how you resolved a conflict and reuse it next time
git config --global rerere.enabled true

# Prune deleted remote branches on every fetch
git config --global fetch.prune true

git maintenance start registers the repository and schedules tasks with cron, launchd or the Windows Task Scheduler. rerere ("reuse recorded resolution") helps when you rebase a long-lived branch repeatedly. See Git branching strategies for ways to avoid long-lived branches in the first place.

How to test a hook before the team relies on it

  1. Run the hook by hand with a sample input. For a commit-msg hook: echo "bad message" > /tmp/msg; .githooks/commit-msg /tmp/msg; echo $? should print a non-zero code.
  2. Try a real commit on a scratch branch with a good and a bad message.
  3. Check it works from a subdirectory of the repo and on every operating system your team uses. Windows users running Git for Windows get Git Bash, but tools such as sed -i differ between GNU and BSD versions.
  4. Keep hooks fast. A pre-commit hook that takes 30 seconds teaches people to use --no-verify.
  5. Print a clear message on failure that says what to change, not just "hook failed".

Moving scripts into CI

Local hooks help individuals. Team rules belong in the pipeline too. Run the commit message check over every commit in a merge request, scan for secrets, and reject large files there, so --no-verify cannot bypass them. Our GitHub Actions workflows and GitLab CI/CD examples show where such checks fit.

If you want structured practice with Git, hooks and pipelines, the DevOps training runs in our Kharadi, Pune classroom and live online.

Frequently asked questions

How do I share Git hooks with my team?

Commit them to a folder such as .githooks and have each developer run git config core.hooksPath .githooks, or use a hook manager like the pre-commit framework. Clones do not copy hooks automatically.

Can developers bypass Git hooks?

Yes. git commit --no-verify and git push --no-verify skip the relevant client hooks. Enforce important rules again in CI and with branch protection on the server.

How do I create a custom Git command?

Put an executable script named git-name on your PATH and run it as git name. For one-liners, use git config --global alias.name "command".

Is it safe to delete merged branches automatically?

Local deletion with git branch -d is safe because it refuses unmerged branches. For remote branches, run a dry run first and exclude protected and release branches.

Should I write Git scripts in Bash or Python?

Bash suits short wrappers around Git commands. Use Python for scripts with complex logic, API calls to GitHub or GitLab, or that must run the same way on Windows.

What does git maintenance start do?

It registers the current repository for background maintenance and schedules tasks such as prefetching and commit-graph updates through the operating system's scheduler.

How do I find what is making my repository large?

Pipe git rev-list --objects --all into git cat-file --batch-check and sort by size, as in script 12. Large blobs in history need a history rewrite to remove.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.