Using Bash in Git Workflows

Su Suriya Ravichandran Updated 06 Dec 2026
21 min read ·Lesson 174 of 205

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:

HookWhen Git runs itInputA non-zero exit status...
pre-commitbefore the commit message is asked fornoneaborts the commit
commit-msgafter the message is written$1: path of a file with the messageaborts the commit
pre-pushbefore anything is sent$1, $2: remote name and URL; on standard input, one line per ref: LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHAaborts 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 --check is 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 -n passes the staged version of a script to bash -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 without shopt -s extglob (lesson 153).
  • The branch and a clean tree. git branch --show-current must match the release branch (an empty result, a detached HEAD, is reported as such), and git status --porcelain must print nothing. If it prints something, git status --short shows the user what.
  • In sync with the remote. git fetch REMOTE BRANCH stores the remote branch's latest commit in FETCH_HEAD. git rev-list --left-right --count HEAD...FETCH_HEAD prints 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 through BASH_REMATCH (lesson 69), and one arithmetic command increments the right part and resets the parts after it. Without any earlier tag, the script starts from v0.0.0.
  • Release notes from the history. git log --no-merges --format='- %s (%h)' v1.4.2..HEAD lists the subject and short hash of every commit since the last tag, which is where consistent commit messages, as enforced by the commit-msg hook 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. -n performs 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

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Using Bash in Git Workflows and get answers drawn from it.

Signed-in readers only.