Using Bash in Git Workflows
Git is a command-line program, and almost everything it does can be started, inspected and checked from a Bash script. Teams use this in three main places: hooks, small scripts Git runs automatically at certain moments (before a commit is recorded, before a push), which catch problems before they reach anyone else; workflow scripts, such as a release script that checks the repository's state, creates a version tag and pushes it in one reliable step; and maintenance tasks, such as cleaning up old branches.
The difficulty is not running Git commands but reading their results reliably. Git's normal output is written for people: it changes between versions, follows the user's language and color settings, and quotes unusual file names. This lesson shows the commands and options designed for scripts, then builds two hooks and a release script.
Asking Git About the Repository
Where is the repository, and which branch is this?
git rev-parse is Git's question-answering command for scripts:
git rev-parse --show-toplevel # the repository's top folder
git rev-parse --abbrev-ref HEAD # the current branch
git branch --show-current # the current branch (Git 2.22 or later)
git rev-parse --short HEAD # the current commit, abbreviated
/srv/t174/app
main
main
ec952b3
Outside a repository, it fails with status 128, which is how a script detects that it is not in one:
$ cd /srv; git rev-parse --show-toplevel; echo "status $?"
fatal: not a git repository (or any of the parent directories): .git
status 128
Scripts often start with cd "$(git rev-parse --show-toplevel)", so that relative paths work no matter which subfolder the script was started from.
When no branch is checked out (a detached HEAD, for example after checking out a tag), the two branch commands answer differently:
detached: [] [HEAD]
git branch --show-current prints nothing, while git rev-parse --abbrev-ref HEAD prints the word HEAD. A script that compares the branch with main works with either, but one that uses the name in a message or a file name must handle both cases.
git rev-parse --verify --quiet NAME checks whether a name (a branch, a tag, a commit) exists. It prints nothing and returns 1 when it does not, which makes it a clean test:
git rev-parse --verify --quiet v9.9; echo "verify missing: $?"
verify missing: 1
Is the working tree clean?
Many scripts must refuse to run while there are uncommitted changes. In a test repository with one modified file, one new staged file and one untracked file whose name contains a space:
git status --porcelain
M README.md
A notes.txt
?? "new file.txt"
--porcelain produces the porcelain format, a stable format meant for scripts: it does not change between Git versions and ignores the user's color and language settings. Each line starts with two status letters, the first for the staging area (the index) and the second for the working tree: M is modified but not staged, A is a new staged file, and ?? is untracked. The name with a space is shown in double quotes, which a script would have to undo. With -z, names are never quoted and each entry ends with a NUL byte instead of a newline:
git status --porcelain=v1 -z | od -c | head -3
0000000 M R E A D M E . m d \0 A
0000020 n o t e s . t x t \0 ? ? n e w
0000040 f i l e . t x t \0
For the simple question "is there anything at all?", testing whether the output is empty is enough:
if [[ -n $(git status --porcelain) ]]; then
echo "uncommitted changes" >&2
exit 1
fi
git diff --quiet answers more specific questions through its exit status alone: 0 means no differences and 1 means there are some. Without options it compares the working tree with the index (unstaged changes); with --cached it compares the index with the last commit (staged changes):
diff --quiet (unstaged): 1
diff --cached --quiet: 1
git diff --name-only and git diff --cached --name-only list the files concerned, one per line:
notes.txt
README.md
(The first line is from --cached, the second without it.) For scripts that must handle every possible file name, -z again gives NUL-separated output, which mapfile -d '' reads into an array (lesson 112):
mapfile -d '' -t files < <(git diff --cached --name-only -z --diff-filter=ACMR)
--diff-filter=ACMR keeps only files that were Added, Copied, Modified or Renamed, so deleted files, which no longer have content to check, are left out.
Looping over branches
git for-each-ref lists branches and tags in a format the script chooses, which is far more reliable than parsing git branch, whose output marks the current branch with * and changes with settings. --merged=main and --no-merged=main select branches whose last commit is, or is not, already part of main. In a test repository with three branches besides main:
echo "--- merged into main:"
git for-each-ref --merged=main --format='%(refname:short)' refs/heads/
echo "--- not merged:"
git for-each-ref --no-merged=main --format='%(refname:short) %(committerdate:short) %(subject)' refs/heads/
echo "--- deleting merged branches:"
git for-each-ref --merged=main --format='%(refname:short)' refs/heads/ |
while IFS= read -r b; do
[[ $b == main ]] && continue
git branch --quiet --delete -- "$b" && echo "deleted $b"
done
git branch --format='%(refname:short)'
--- merged into main:
feature/login
fix/typo
main
--- not merged:
wip/search 2026-11-25 feat: start search
--- deleting merged branches:
deleted feature/login
deleted fix/typo
main
wip/search
git branch --delete (-d) refuses to delete a branch that is not merged, so even a mistake in the loop cannot lose work; -D would force it. The -- before the branch name stops a name beginning with - from being read as an option (lesson 155).
Git Hooks
A hook is an executable file with a special name that Git runs at a specific moment. Hooks live in .git/hooks/ by default. That folder is not part of the repository's content, so its files are not shared through clones. To share hooks with a team, store them in a normal folder of the repository and point Git at it:
git config core.hooksPath .githooks
Each person still has to run this command once per clone: Git deliberately never runs hooks automatically from a cloned repository, because that would let anyone who publishes a repository run code on the machines of the people who clone it.
The most useful client-side hooks for scripts are:
| Hook | When Git runs it | Input | A non-zero exit status... |
|---|---|---|---|
pre-commit | before the commit message is asked for | none | aborts the commit |
commit-msg | after the message is written | $1: path of a file with the message | aborts the commit |
pre-push | before anything is sent | $1, $2: remote name and URL; on standard input, one line per ref: LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHA | aborts the push |
A hook must be executable (chmod +x), and since Git runs it directly, its shebang line decides the interpreter. Git runs hooks from the top folder of the working tree. Anyone can skip pre-commit and commit-msg with git commit --no-verify (and pre-push with git push --no-verify), so hooks are a helpful first check, not an enforcement mechanism. Rules that must hold are enforced again on the server or in CI (lesson 177).
A pre-commit hook
This hook checks the files about to be committed:
#!/usr/bin/env bash
# pre-commit: check what is about to be committed (the staged versions of files)
set -uo pipefail
problems=0
fail() { echo "pre-commit: $*" >&2; problems=1; }
# 1. Whitespace errors and leftover conflict markers, using Git's own check
if ! git diff --cached --check >&2; then
fail "fix the whitespace errors or conflict markers listed above"
fi
# Staged files that were added, copied, modified or renamed (not deleted),
# NUL-separated so that any file name is handled correctly
mapfile -d '' -t files < <(git diff --cached --name-only -z --diff-filter=ACMR)
for file in "${files[@]}"; do
# 2. Files that look like secrets
case ${file##*/} in
.env|*.pem|*.key|id_rsa|id_ed25519)
fail "$file looks like a secret; it should not be committed" ;;
esac
# 3. Large files (the staged size, not the size in the working tree)
size=$(git cat-file -s ":$file")
if (( size > 1024 * 1024 )); then
fail "$file is $(( size / 1024 )) KiB; large files do not belong in Git"
fi
# 4. Shell scripts must at least parse
if [[ $file == *.sh ]]; then
if ! errors=$(git show ":$file" | bash -n 2>&1); then
fail "$file has a syntax error:"
printf ' %s\n' "${errors//$'\n'/$'\n' }" >&2
fi
fi
done
if (( problems )); then
echo "pre-commit: commit aborted (use 'git commit --no-verify' to skip these checks)" >&2
fi
exit "$problems"
The most important detail is what it checks. A commit records the staged version of each file, which can differ from the file in the working tree: someone may fix an error in the file but forget to run git add again. A hook that checks the working-tree file would then approve a commit that contains the broken version. This hook therefore reads the staged content:
git diff --cached --checkis Git's built-in check for trailing whitespace and leftover conflict markers (<<<<<<<) in the staged changes; it prints each problem and returns non-zero.git cat-file -s ":$file"prints the size of the staged version. The name:path(a colon, then the path) means "this file as it is in the index".git show ":$file" | bash -npasses the staged version of a script tobash -n, which checks the syntax without running anything (lesson 126). The error messages are captured and indented with a pattern replacement on the newlines (lesson 152).
The hook collects all problems before exiting, so that one commit attempt reports everything at once.
A commit-msg hook
Many teams use a fixed form for commit messages, such as the Conventional Commits style: a type, an optional scope, a colon and a short description (fix(api): handle empty input). Tools can then build change logs and choose version numbers from the history. This hook enforces the form and a maximum length of 72 characters for the summary line:
#!/usr/bin/env bash
# commit-msg: require a summary line like "fix: handle empty input" or
# "feat(api): add login", at most 72 characters long
set -uo pipefail
msg_file=$1
# The first line that is not empty and not a comment is the summary.
summary=$(grep -v -m 1 -E '^(#|[[:space:]]*$)' -- "$msg_file")
case $summary in
"Merge "*|"Revert "*|"fixup! "*|"squash! "*) exit 0 ;; # made by Git itself
esac
types='feat|fix|docs|refactor|test|chore|build|ci'
if [[ ! $summary =~ ^($types)(\([a-z0-9-]+\))?!?:\ [^[:space:]] ]]; then
echo "commit-msg: the summary line must look like 'TYPE: description'" >&2
echo "commit-msg: TYPE is one of: ${types//|/, } (optionally with a scope, e.g. 'fix(api): ...')" >&2
echo "commit-msg: got: '$summary'" >&2
exit 1
fi
if (( ${#summary} > 72 )); then
echo "commit-msg: the summary line has ${#summary} characters; keep it to 72 or fewer" >&2
exit 1
fi
Git passes the path of a temporary file containing the message as $1. When the message is written in an editor, that file also contains comment lines starting with # (which Git removes later), so the hook takes the first line that is neither a comment nor empty: grep -v -m 1 prints the first line that does not match. Messages that Git writes itself, such as Merge branch ... and the fixup! commits of interactive rebasing, are let through. In the regular expression, ($types) matches one of the listed types, ( 0 [a-z0-9-]+ 1 )? an optional scope in parentheses, !? an optional ! that marks a breaking change, and \ [^[:space:]] requires a space and then real text after the colon.
Testing the hooks
Both hooks were saved in .githooks/ of a test repository, made executable, and activated with git config core.hooksPath .githooks. Committing the hooks themselves already ran them:
$ git commit -q -m 'chore: add shared Git hooks'
[status 0]
Commit messages that break the rules are refused, and a correct one is accepted:
$ git commit -q -m 'updated readme'
commit-msg: the summary line must look like 'TYPE: description'
commit-msg: TYPE is one of: feat, fix, docs, refactor, test, chore, build, ci (optionally with a scope, e.g. 'fix(api): ...')
commit-msg: got: 'updated readme'
[status 1]
$ git commit -q -m 'docs: describe the deployment steps for the staging and production servers in detail'
commit-msg: the summary line has 84 characters; keep it to 72 or fewer
[status 1]
$ git commit -q -m 'docs(readme): describe deployment'
[status 0]
Next, four problems were staged at once: a line with a trailing space in README.md, a script broken.sh with an if that has no fi, a .env file with an API key, and a 2 MB data.bin:
$ git commit -q -m 'feat: add things'
README.md:3: trailing whitespace.
+line with trailing space
pre-commit: fix the whitespace errors or conflict markers listed above
pre-commit: .env looks like a secret; it should not be committed
pre-commit: broken.sh has a syntax error:
bash: line 4: syntax error: unexpected end of file
pre-commit: data.bin is 1953 KiB; large files do not belong in Git
pre-commit: commit aborted (use 'git commit --no-verify' to skip these checks)
[status 1]
Then .env and data.bin were unstaged and deleted, the trailing space was fixed and staged, and broken.sh was fixed in the working tree (a fi appended) without staging it again:
$ git commit -q -m 'feat: add broken script'
pre-commit: broken.sh has a syntax error:
bash: line 4: syntax error: unexpected end of file
pre-commit: commit aborted (use 'git commit --no-verify' to skip these checks)
[status 1]
The hook still found the error, because the staged version of broken.sh was still broken. After git add broken.sh, the commit went through:
$ git commit -q -m 'feat: add deployment check script'
[status 0]
A Complete Example: A Release Script
Making a release by hand involves several steps that are easy to get wrong: being on the right branch, having no uncommitted changes, being in sync with the shared repository, choosing the next version number, writing the release notes, creating the tag and pushing it. A missed step produces a tag on the wrong commit or a release that contains changes nobody reviewed. release.sh performs every step, checks everything first, and stops at the first problem.
Versions follow semantic versioning: vMAJOR.MINOR.PATCH, where a patch release only fixes bugs, a minor release adds features, and a major release contains incompatible changes. Releasing minor after v1.4.2 gives v1.5.0.
#!/usr/bin/env bash
#
# release.sh - tag a new release version and push it
#
# Usage: release.sh [-n] [-r REMOTE] [-b BRANCH] major|minor|patch
# -n dry run: show what would happen, change nothing
# -r REMOTE remote to check and push to (default: origin)
# -b BRANCH branch releases are made from (default: main)
#
# Versions are annotated tags named vMAJOR.MINOR.PATCH. The new tag's message
# lists the commits since the previous release. Run it anywhere inside the
# repository.
#
# Exit status: 0 released (or dry run done), 1 a check failed, 2 usage error
set -uo pipefail
dry_run=0 remote=origin branch=main
usage() { echo "usage: ${0##*/} [-n] [-r REMOTE] [-b BRANCH] major|minor|patch" >&2; exit 2; }
die() { echo "${0##*/}: $*" >&2; exit 1; }
info() { echo "==> $*"; }
while getopts ':nr:b:' opt; do
case $opt in
n) dry_run=1 ;;
r) remote=$OPTARG ;;
b) branch=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 1 )) || usage
part=$1
[[ $part == @(major|minor|patch) ]] || usage
# --- where are we? -----------------------------------------------------------
top=$(git rev-parse --show-toplevel 2>/dev/null) || die "not inside a Git repository"
cd -- "$top" || exit 1
current=$(git branch --show-current)
[[ $current == "$branch" ]] || die "releases are made from '$branch', but you are on '${current:-a detached HEAD}'"
if [[ -n $(git status --porcelain) ]]; then
git status --short >&2
die "the working tree has uncommitted changes (listed above)"
fi
# --- is the branch identical to the remote one? ------------------------------
info "fetching $remote/$branch"
git fetch --quiet -- "$remote" "$branch" || die "could not fetch '$branch' from '$remote'"
read -r ahead behind < <(git rev-list --left-right --count "HEAD...FETCH_HEAD")
(( behind == 0 )) || die "'$branch' is $behind commit(s) behind $remote; pull first"
(( ahead == 0 )) || die "'$branch' has $ahead commit(s) not pushed to $remote; push or review them first"
# --- work out the new version --------------------------------------------------
last=$(git describe --tags --abbrev=0 --match 'v[0-9]*.[0-9]*.[0-9]*' 2>/dev/null)
if [[ -z $last ]]; then
last_version=v0.0.0
range=HEAD
else
last_version=$last
range=$last..HEAD
fi
[[ $last_version =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] || die "cannot read the version in tag '$last_version'"
major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]} patch=${BASH_REMATCH[3]}
case $part in
major) (( major++, minor = 0, patch = 0 )) ;;
minor) (( minor++, patch = 0 )) ;;
patch) (( patch++ )) ;;
esac
new=v$major.$minor.$patch
git rev-parse --quiet --verify "refs/tags/$new" > /dev/null && die "tag $new already exists"
changes=$(git log --no-merges --format='- %s (%h)' "$range")
[[ -n $changes ]] || die "no commits since $last_version; nothing to release"
notes="Release $new
Changes since ${last:-the start of the project}:
$changes"
info "new version: ${last:-(none)} -> $new"
printf '%s\n' "$notes" | sed 's/^/ /'
if (( dry_run )); then
info "dry run: no tag created, nothing pushed"
exit 0
fi
# --- tag and push ----------------------------------------------------------------
git tag --annotate --file=- -- "$new" <<< "$notes" || die "could not create tag $new"
# The branch is already identical on the remote (checked above), so only the
# tag needs to be pushed.
if ! git push --quiet -- "$remote" "refs/tags/$new"; then
git tag --delete -- "$new" > /dev/null
die "push failed; the local tag $new was removed so the release can be retried"
fi
info "released $new"
How It Works
- Works from any subfolder. The script moves to the top of the repository with
git rev-parse --show-toplevel, and reports clearly when it is not in a repository at all. - Pattern check of the argument.
[[ $part == @(major|minor|patch) ]]uses an extended pattern, which[[ ]]accepts withoutshopt -s extglob(lesson 153). - The branch and a clean tree.
git branch --show-currentmust match the release branch (an empty result, a detached HEAD, is reported as such), andgit status --porcelainmust print nothing. If it prints something,git status --shortshows the user what. - In sync with the remote.
git fetch REMOTE BRANCHstores the remote branch's latest commit inFETCH_HEAD.git rev-list --left-right --count HEAD...FETCH_HEADprints two numbers: commits only on the local side and commits only on the remote side. Both must be 0. Being behind means someone else pushed changes that would be left out of the release notes; being ahead means local commits that nobody else has seen would be tagged. - The last version.
git describe --tags --abbrev=0 --match 'v[0-9]*.[0-9]*.[0-9]*'finds the most recent tag reachable from the current commit that matches the version pattern. The regular expression then splits it into three numbers throughBASH_REMATCH(lesson 69), and one arithmetic command increments the right part and resets the parts after it. Without any earlier tag, the script starts fromv0.0.0. - Release notes from the history.
git log --no-merges --format='- %s (%h)' v1.4.2..HEADlists the subject and short hash of every commit since the last tag, which is where consistent commit messages, as enforced by thecommit-msghook above, pay off. No commits means nothing to release. - An annotated tag.
git tag --annotate --file=-creates a tag object with its own message, author and date (unlike a lightweight tag, which is only a name);--file=-reads the message from standard input, here a here-string (lesson 64), so the multi-line notes need no temporary file. - Push only the tag, and undo on failure. The branch was already checked to be identical on the remote, so only the tag is pushed. If the push fails, the local tag is deleted, so that running the script again after fixing the problem does not stop at "tag already exists".
- Dry run.
-nperforms every check and shows the version and notes, then stops before changing anything.
Running the Complete Example
The test used a repository with four commits and a local bare repository (git clone --bare) as origin, standing in for a hosting service. A dry run and then a real minor release:
$ release.sh -n minor
==> fetching origin/main
==> new version: (none) -> v0.1.0
Release v0.1.0
Changes since the start of the project:
- feat: add deployment check script (50bd183)
- docs(readme): describe deployment (cac12b9)
- chore: add shared Git hooks (75e3e28)
- feat: first version (65eb179)
==> dry run: no tag created, nothing pushed
[status 0]
$ release.sh minor
==> fetching origin/main
==> new version: (none) -> v0.1.0
Release v0.1.0
Changes since the start of the project:
- feat: add deployment check script (50bd183)
- docs(readme): describe deployment (cac12b9)
- chore: add shared Git hooks (75e3e28)
- feat: first version (65eb179)
==> released v0.1.0
[status 0]
The annotated tag carries the release notes, as git tag -n99 shows:
v0.1.0 Release v0.1.0
Changes since the start of the project:
- feat: add deployment check script (50bd183)
- docs(readme): describe deployment (cac12b9)
- chore: add shared Git hooks (75e3e28)
- feat: first version (65eb179)
Each check was then triggered in turn. Running again with no new commits, with an untracked file present, and from a feature branch:
$ release.sh patch
==> fetching origin/main
release.sh: no commits since v0.1.0; nothing to release
[status 1]
$ release.sh patch
?? scratch.txt
release.sh: the working tree has uncommitted changes (listed above)
[status 1]
$ release.sh patch
release.sh: releases are made from 'main', but you are on 'feature/login'
[status 1]
A second clone, standing in for a colleague, pushed a fix to origin. The release was refused until the change had been pulled; then a local commit that had not been pushed blocked it:
$ release.sh patch
==> fetching origin/main
release.sh: 'main' is 1 commit(s) behind origin; pull first
[status 1]
$ release.sh patch
==> fetching origin/main
release.sh: 'main' has 1 commit(s) not pushed to origin; push or review them first
[status 1]
After git push, the patch release contained exactly the two new commits:
$ release.sh patch
==> fetching origin/main
==> new version: v0.1.0 -> v0.1.1
Release v0.1.1
Changes since v0.1.0:
- docs: add step 2 (d837fcb)
- fix: quote the target folder (e1ae21d)
==> released v0.1.1
[status 0]
A tag v0.1.2 was then created on another branch, so that the next patch version was already taken:
$ release.sh patch
==> fetching origin/main
release.sh: tag v0.1.2 already exists
[status 1]
To test a failed push, a pre-receive hook (a server-side hook) was added to the bare repository that rejects every push. The script created the tag, the push was rejected, and the local tag was removed again; git tag --list afterwards showed only v0.1.0 and v0.1.1. After the hook was removed, the same command succeeded:
$ release.sh major
==> fetching origin/main
==> new version: v0.1.1 -> v1.0.0
Release v1.0.0
Changes since v0.1.1:
- docs: add step 3 (3b0215f)
remote: origin: pushes are frozen today
To /srv/t174/origin.git
! [remote rejected] v1.0.0 -> v1.0.0 (pre-receive hook declined)
error: failed to push some refs to '/srv/t174/origin.git'
release.sh: push failed; the local tag v1.0.0 was removed so the release can be retried
[status 1]
$ release.sh major
==> fetching origin/main
==> new version: v0.1.1 -> v1.0.0
Release v1.0.0
Changes since v0.1.1:
- docs: add step 3 (3b0215f)
==> released v1.0.0
[status 0]
The remote now holds all three tags:
$ git ls-remote --tags origin | grep -v '\^{}'
02e1e64a6f14a602e6dddf42bf3236815e634911 refs/tags/v0.1.0
6af2656719d55afbf86bafae6101edc84abddfee refs/tags/v0.1.1
1884f95f58b14426159fc9e231c6d7e2fc0545b8 refs/tags/v1.0.0
(git ls-remote lists an annotated tag twice, once as the tag object and once with ^{} for the commit it points to; the grep -v hides the second form.) Wrong arguments and running it outside a repository are reported:
$ release.sh -x
usage: release.sh [-n] [-r REMOTE] [-b BRANCH] major|minor|patch
[status 2]
$ release.sh huge
usage: release.sh [-n] [-r REMOTE] [-b BRANCH] major|minor|patch
[status 2]
$ cd /tmp && release.sh patch
release.sh: not inside a Git repository
[status 1]
The script can also be made available as a Git command: an executable named git-release in a folder on PATH runs as git release minor, because Git looks for git-NAME programs when it does not know a subcommand. A symbolic link is enough; in the test repository, which by then had two unpushed commits, git release -n patch ran the script, and the messages carried the new name, since they use ${0##*/}:
==> fetching origin/main
git-release: 'main' has 2 commit(s) not pushed to origin; push or review them first