Using ShellCheck in a Development Workflow

Su Suriya Ravichandran Updated 06 Dec 2026
20 min read ·Lesson 190 of 205

Lesson 162 introduced ShellCheck: how to run it, how to read its reports, what the most common checks mean and how to silence a check deliberately. Knowing the tool is only half of the benefit, though. ShellCheck helps most when nobody has to remember to run it, when every developer and every automated system runs the same version with the same settings, and when a script with a new problem cannot quietly reach the main branch.

This lesson builds that setup step by step for a repository of shell scripts. It places ShellCheck at four points of the development cycle, each catching problems at a different moment:

StageWhen it runsWhat it gives
Editorwhile typinginstant feedback, cheapest moment to fix
Git pre-commit hookon git commitstops new problems before they enter history
Continuous integration (CI)on every push and pull requestan enforced gate that no one can skip
Baseline checkin CI, for older codelets a project adopt ShellCheck without fixing everything first

All stages call one shared script, so they always agree about which files are checked and how.

Step 1: Make Every Stage Agree

Three things decide what ShellCheck reports: its version, its configuration and which files it is given. If any of these differ between a laptop and the CI server, developers see "passes for me, fails in CI" problems, and trust in the tool erodes quickly.

Pin the Version

New ShellCheck releases add checks, so an upgrade can turn a clean repository into a failing one overnight. Distribution packages also lag behind: Ubuntu, Homebrew and the CI image may each install a different version. Agree on one version and install it the same way everywhere. Practical options include:

  • The official release binaries from the ShellCheck GitHub releases page: a single static executable, easy to download in CI.
  • The Docker image koalaman/shellcheck, with a tag per version, for example docker run --rm -v "$PWD:/mnt" koalaman/shellcheck:v0.10.0 script.sh.
  • The Python package shellcheck-py, which installs a pinned ShellCheck binary with pip, convenient in projects that already use Python tooling.

Version 0.10.0 is used in the examples in this lesson; the right choice is whatever version the team decides on, written down in the repository and upgraded deliberately.

Commit the Configuration

Settings belong in a .shellcheckrc file at the top of the repository, not in individual developers' editor settings or in a CI command line. ShellCheck looks for this file in the directory of each checked script and its parent directories, so every stage that checks the repository picks it up automatically:

# .shellcheckrc - shared by editors, the pre-commit hook and CI

# Follow files loaded with "source" and resolve their paths from each script's folder
external-sources=true
source-path=SCRIPTDIR

# Optional checks this project wants on top of the defaults
enable=check-set-e-suppressed,deprecate-which

ShellCheck has optional checks that are off by default. check-set-e-suppressed warns when a function is called in a place where set -e is switched off, such as an if condition, so failures inside the function no longer stop the script (lesson 119); deprecate-which suggests command -v instead of which. Run shellcheck --list-optional to see the optional checks your version offers before enabling any; names can change between versions.

Keep disable= lines out of .shellcheckrc unless the whole team agrees: a project-wide disable hides that class of bug in every script, now and in the future.

Define Which Files Are Shell Scripts

shellcheck *.sh misses many real scripts, because executables in bin/ usually have no extension, and it may include files that are not meant for ShellCheck. A reliable rule is: a file is a shell script if it ends in .sh or .bash, or if its first line is a shebang for sh, bash, dash or ksh, the dialects ShellCheck supports.

Step 2: One Lint Script for Every Stage

The following script implements the rules above. It is the single entry point used by developers, the Git hook and CI:

#!/usr/bin/env bash
#
# lint.sh - run ShellCheck on the shell scripts of this repository
#
# Usage: scripts/lint.sh               check every tracked shell script
#        scripts/lint.sh --staged      check scripts staged for the next commit
#        scripts/lint.sh --changed REF check scripts changed since REF (e.g. origin/main)
#
# Shell scripts are recognised by extension (.sh, .bash) or by a sh/bash/dash/ksh
# shebang. LINT_FORMAT selects the output format (default: tty); ShellCheck
# itself reads extra options from the SHELLCHECK_OPTS environment variable.
# Exit status: 0 clean, 1 problems found, 2 ShellCheck missing or failed to run.

set -euo pipefail
cd "$(git rev-parse --show-toplevel)"

if ! command -v shellcheck > /dev/null; then
  echo "lint.sh: shellcheck is not installed" >&2
  exit 2
fi

is_shell_script() {
  local first=""
  case $1 in
    *.sh | *.bash) return 0 ;;
  esac
  IFS= read -r first < "$1" || true
  [[ $first =~ ^\#!.*[/[:space:]](ba|da|k)?sh([[:space:]]|$) ]]
}

case ${1:-} in
  --staged)  list=(git diff --cached --name-only -z --diff-filter=ACMR) ;;
  --changed) list=(git diff --name-only -z --diff-filter=ACMR "${2:?--changed needs a git reference}...HEAD") ;;
  '')        list=(git ls-files -z) ;;
  *)         echo "Usage: scripts/lint.sh [--staged | --changed REF]" >&2; exit 2 ;;
esac

files=()
while IFS= read -r -d '' f; do
  [[ -f $f ]] && is_shell_script "$f" && files+=("$f")
done < <("${list[@]}")

if (( ${#files[@]} == 0 )); then
  echo "lint.sh: no shell scripts to check"
  exit 0
fi

version=$(shellcheck --version | sed -n 's/^version: //p')
echo "lint.sh: checking ${#files[@]} file(s) with ShellCheck $version" >&2
status=0
shellcheck --format="${LINT_FORMAT:-tty}" "${files[@]}" || status=$?
(( status <= 1 )) || echo "lint.sh: shellcheck failed to run (status $status)" >&2
exit "$status"

How It Works

  • It always runs from the repository root. git rev-parse --show-toplevel prints the top directory, so the script behaves the same whether it is started from the root, from a subdirectory, or by Git as a hook.
  • Git decides which files exist. git ls-files lists tracked files only, so build output, downloaded tools and files in .gitignore are never checked. The three modes differ only in the Git command that produces the list: all tracked files, the files staged for the next commit (git diff --cached), or the files changed on a branch compared with a reference. --diff-filter=ACMR keeps added, copied, modified and renamed files and leaves out deleted ones, which no longer exist.
  • Names are NUL-separated. -z in the Git commands and read -r -d '' in the loop handle file names containing spaces or newlines (lesson 112).
  • is_shell_script accepts .sh and .bash files directly and otherwise reads the first line. The regular expression requires #!, then anything, then a / or a space, then sh, bash, dash or ksh followed by a space or the end of the line. That accepts #!/bin/sh, #!/usr/bin/env bash and #!/bin/bash -e, and rejects #!/usr/bin/env python3 and #!/usr/bin/env zsh. ShellCheck does not support zsh, so zsh scripts must be left out rather than checked with the wrong rules.
  • The commands are stored in arrays (list=(git diff ...)) and run with "${list[@]}", which keeps every argument intact without eval (lesson 157).
  • The exit status is passed through. ShellCheck exits with 1 when it finds problems and with 2 to 4 when it could not do its job. The script reports both, and a missing ShellCheck gets its own status 2, so callers can tell "your code has problems" apart from "the tool is broken".
  • The version is printed on every run. When results differ between two machines, the first line of the log already answers the most likely question.

Running It

A sample repository contains eight files: shell scripts with and without extensions, a sourced helper without a shebang, a Python script, a zsh script and a text file. The script picks exactly the five shell scripts:

bin/clean-tool        #!/bin/sh                 checked
bin/deploy            #!/usr/bin/env bash       checked
bin/flags             #!/bin/bash -e            checked
scripts/common.bash   (no shebang, .bash)       checked
scripts/lint.sh       #!/usr/bin/env bash       checked
tools/report.py       #!/usr/bin/env python3    skipped
bin/zz                #!/usr/bin/env zsh        skipped
notes.txt             (plain text)              skipped

With the compact gcc output format (lesson 162), a run looks like this:

$ LINT_FORMAT=gcc scripts/lint.sh; echo "status $?"
lint.sh: checking 5 file(s) with ShellCheck 0.10.0
bin/deploy:2:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
bin/deploy:2:4: note: Double quote to prevent globbing and word splitting. [SC2086]
bin/deploy:3:14: note: Use $(...) notation instead of legacy backticks `...`. [SC2006]
status 1

Because the progress line goes to standard error, standard output contains only ShellCheck's findings, which later steps can process. A Makefile target such as lint: ; scripts/lint.sh or a package script can wrap the same command, so developers have one obvious way to run the check by hand.

Step 3: Editor Integration

The earliest and cheapest moment to fix a problem is while the line is being written. Most editors can run ShellCheck on the open file and underline problems:

  • Visual Studio Code: the "ShellCheck" extension, or the Bash IDE extension, whose language server runs ShellCheck when it is installed.
  • Vim and Neovim: plugins such as ALE or nvim-lint, or any client of bash-language-server.
  • Emacs: Flycheck includes a ShellCheck checker.
  • JetBrains IDEs: the Shell Script plugin uses ShellCheck for inspections.

Because the editor runs ShellCheck on the file inside the repository, it reads the committed .shellcheckrc automatically. Make sure the editor uses the pinned ShellCheck version rather than an older one from the system package manager; most integrations have a setting for the executable path.

Editor integration is a convenience, not a guarantee: it depends on each developer's setup. The next two stages are what actually enforce the rules.

Step 4: A Git Pre-commit Hook

Git runs the executable .git/hooks/pre-commit, if it exists, before creating a commit; if the hook exits with a non-zero status, the commit is cancelled. Hooks live inside .git, which is not versioned, so the hook script itself is committed in scripts/ and each developer links it once:

#!/usr/bin/env bash
# pre-commit - Git hook: refuse commits that add ShellCheck problems to staged scripts.
# Install once per clone:  ln -s ../../scripts/pre-commit .git/hooks/pre-commit
# Bypass in an emergency:  git commit --no-verify

status=0
LINT_FORMAT=${LINT_FORMAT:-gcc} "$(git rev-parse --show-toplevel)/scripts/lint.sh" --staged || status=$?
case $status in
  0) exit 0 ;;
  2) echo "pre-commit: ShellCheck could not run; commit allowed, CI will check" >&2; exit 0 ;;
  *) echo "pre-commit: fix the problems above, then commit again" >&2; exit 1 ;;
esac

Design decisions in this hook:

  • Only staged files are checked (--staged), so a commit is not blocked by unrelated problems elsewhere in the repository, and the hook stays fast.
  • A missing or broken ShellCheck does not block commits. Blocking would punish developers for their machine setup rather than their code, and CI checks again anyway. Teams that prefer strictness can turn status 2 into a failure.
  • The compact gcc format fits better in a terminal than the multi-line default format. ${LINT_FORMAT:-gcc} lets a developer override it.
  • The symbolic link ../../scripts/pre-commit is relative to .git/hooks/, so the hook always runs the current version from the working tree.

In the sample repository, committing a new script that contains an unchecked cd is refused:

$ git add bin/sync
$ git commit -m "add sync"
lint.sh: checking 1 file(s) with ShellCheck 0.10.0
bin/sync:2:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
bin/sync:2:4: note: Double quote to prevent globbing and word splitting. [SC2086]
pre-commit: fix the problems above, then commit again
$ echo $?
1

One limitation is worth knowing: the hook checks the files as they are in the working tree, not exactly what is staged. If only part of a file's changes were staged with git add -p, the check may see different content from what will be committed. CI, which checks the committed content, closes that gap.

Using the pre-commit Framework Instead

Projects that already use the pre-commit framework (a Python tool that manages hooks from a configuration file) can let it install and pin ShellCheck. A .pre-commit-config.yaml entry using the shellcheck-py package looks like this:

repos:
  - repo: https://github.com/shellcheck-py/shellcheck-py
    rev: v0.10.0.1
    hooks:
      - id: shellcheck

The framework passes staged files to ShellCheck itself, selecting them by file type, which includes detecting shell shebangs. The official koalaman/shellcheck-precommit repository provides an equivalent hook that runs ShellCheck in Docker. Either way, the hook version is pinned in a committed file, which solves the version problem from Step 1 for local commits.

Step 5: Enforcing the Check in CI

Hooks can be skipped with --no-verify or simply never installed. A CI job that runs on every push and pull request is the stage that cannot be bypassed. In GitHub Actions, a workflow file such as .github/workflows/shellcheck.yml might look like this:

name: shellcheck

on:
  push:
    branches: [main]
  pull_request:

jobs:
  shellcheck:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4

      - name: Install the pinned ShellCheck version
        run: |
          v=v0.10.0
          curl -fsSL "https://github.com/koalaman/shellcheck/releases/download/$v/shellcheck-$v.linux.x86_64.tar.xz" | tar -xJ
          echo "$PWD/shellcheck-$v" >> "$GITHUB_PATH"

      - name: Lint all shell scripts
        shell: bash
        run: LINT_FORMAT=gcc scripts/lint.sh | scripts/gcc-to-annotations.sh

      - name: Require a reason for every disabled check
        run: scripts/check-directives.sh

Points worth understanding:

  • The pinned binary is put first in PATH by appending its directory to the file named in $GITHUB_PATH. GitHub's Ubuntu runners come with a ShellCheck package preinstalled, but its version is chosen by the runner image, not by the project.
  • shell: bash matters. Without it, GitHub runs run: steps with bash -e; with it, the step runs with bash --noprofile --norc -eo pipefail. Only with pipefail does a failure of lint.sh on the left side of the pipe fail the step (lesson 120); otherwise the step would report the status of the annotation script, which always succeeds.
  • The same lint.sh is used as on developer machines, so local and CI results match when the versions match.

The workflow uses two small helper scripts, explained next. Other CI systems (GitLab CI, Jenkins, and so on) need only the same commands in their own configuration format (lesson 177).

Showing Problems on the Pull Request

GitHub Actions turns specially formatted lines in a job's output into annotations, which appear directly on the affected lines in a pull request's file view. The format is ::error file=PATH,line=N,col=N,title=TITLE::MESSAGE, with warning and notice as the other levels. A short awk program translates ShellCheck's gcc format:

#!/usr/bin/env bash
# gcc-to-annotations.sh - turn ShellCheck's gcc-format lines into GitHub Actions
# annotations, so problems appear on the changed lines of a pull request.
# Every input line is also echoed unchanged, keeping the plain log readable.
awk '
  { print }
  match($0, /^[^:]+:[0-9]+:[0-9]+: (error|warning|note): /) {
    split($0, p, ":")
    level = p[4]; sub(/^ /, "", level)
    msg = substr($0, RLENGTH + 1)
    code = ""
    if (match(msg, /\[SC[0-9]+\]$/)) { code = substr(msg, RSTART + 1, RLENGTH - 2); msg = substr(msg, 1, RSTART - 2) }
    kind = (level == "note") ? "notice" : level
    printf "::%s file=%s,line=%s,col=%s,title=%s::%s\n", kind, p[1], p[2], p[3], code, msg
  }
'

The first match recognizes a finding line and sets RLENGTH to the length of the file:line:col: level: prefix, so substr can cut out the message. split on : provides file, line, column and level. ShellCheck's note level becomes GitHub's notice. For a branch that added a script with backticks, the step prints:

$ LINT_FORMAT=gcc scripts/lint.sh --changed main | scripts/gcc-to-annotations.sh; echo "status $?"
lint.sh: checking 1 file(s) with ShellCheck 0.10.0
bin/build:2:13: note: Use $(...) notation instead of legacy backticks `...`. [SC2006]
::notice file=bin/build,line=2,col=13,title=SC2006::Use $(...) notation instead of legacy backticks `...`.
status 1

(With pipefail enabled, the pipeline's status 1 comes from lint.sh.) The --changed main mode is useful for a quick pull-request check; to use it in CI, check out the full history with fetch-depth: 0 in the actions/checkout step, because the default shallow clone does not contain main.

Reviewing Disabled Checks

Every # shellcheck disable= directive is a place where a warning was overruled. Lesson 162 recommended always explaining why. A small check makes that rule enforceable: a directive must have an ordinary comment directly above it.

#!/usr/bin/env bash
# check-directives.sh - every "# shellcheck disable=" needs a reason: an ordinary
# comment on the line directly above it. Prints offending lines; exit 1 if any.
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"

mapfile -d '' files < <(git grep -l -z -e '# shellcheck disable=' || true)
(( ${#files[@]} > 0 )) || exit 0

awk '
  FNR == 1 { prev = "" }
  /^[[:space:]]*# shellcheck disable=/ {
    if (prev !~ /^[[:space:]]*#/ || prev ~ /^[[:space:]]*# shellcheck /) {
      printf "%s:%d: directive without a reason: %s\n", FILENAME, FNR, $0
      bad = 1
    }
  }
  { prev = $0 }
  END { exit bad }' "${files[@]}"

git grep -l -z lists tracked files containing a directive. The || true is needed because git grep exits with 1 when nothing matches, which pipefail and set -e would otherwise treat as an error in a repository without directives. awk remembers the previous line in prev; FNR == 1 resets it at the start of each file. A directive whose previous line is not a comment, or is itself another shellcheck directive, is reported, and awk exits with 1.

Given this file:

#!/usr/bin/env bash
# RSYNC_FLAGS holds several simple flags from our own config; splitting is intended.
# shellcheck disable=SC2086
rsync -a $RSYNC_FLAGS "$1/" "$2/"
# shellcheck disable=SC2164
cd $3

the check accepts the first directive and rejects the second:

$ scripts/check-directives.sh; echo "status $?"
bin/rsync-mirror:5: directive without a reason: # shellcheck disable=SC2164
status 1

Step 6: Adopting ShellCheck in an Existing Project

Turning on a strict CI check in a project with hundreds of old scripts usually produces hundreds of findings at once. Fixing them all before enabling the check delays the benefit for weeks; ignoring them makes the check useless. A baseline solves the dilemma: record today's findings as known, and fail only on findings that are not in the record. New and edited code must be clean, while old problems are fixed gradually.

#!/usr/bin/env bash
#
# lint-baseline.sh - adopt ShellCheck gradually: fail only on problems that are
# not already recorded in the baseline file.
#
# Usage: scripts/lint-baseline.sh record   write the current findings to the baseline
#        scripts/lint-baseline.sh check    exit 1 if there are findings beyond the baseline
#
# A finding is identified by file and code only ("bin/deploy SC2086"), not by
# line number, so editing other parts of a file does not invalidate the baseline.

set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
baseline=.shellcheck-baseline

findings() {
  local status=0
  LINT_FORMAT=gcc scripts/lint.sh 2> /dev/null > "$1" || status=$?
  (( status <= 1 )) || { echo "lint-baseline.sh: lint.sh failed (status $status)" >&2; exit 2; }
  sed -nE 's/^([^:]+):[0-9]+:[0-9]+: [a-z]+: .*\[(SC[0-9]+)\]$/\1 \2/p' "$1" | LC_ALL=C sort
}

tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

case ${1:-} in
  record)
    findings "$tmp" > "$baseline"
    echo "recorded $(wc -l < "$baseline") known finding(s) in $baseline"
    ;;
  check)
    [[ -f $baseline ]] || { echo "no $baseline; run '$0 record' first" >&2; exit 2; }
    current=$(findings "$tmp")
    new=$(LC_ALL=C comm -13 "$baseline" <(printf '%s\n' "$current" | sed '/^$/d'))
    fixed=$(LC_ALL=C comm -23 "$baseline" <(printf '%s\n' "$current" | sed '/^$/d'))
    if [[ -n $fixed ]]; then
      echo "fixed since the baseline (run '$0 record' to lock in the progress):"
      printf '%s\n' "$fixed" | sed 's/^/  /'
    fi
    if [[ -n $new ]]; then
      echo "NEW findings not in the baseline:"
      # show every reported line whose file and code match a new finding
      printf '%s\n' "$new" | awk '
        NR == FNR { want[$1 " " $2] = 1; next }
        { split($0, p, ":"); code = $NF; gsub(/[][]/, "", code)
          if ((p[1] " " code) in want) print "  " $0 }' - "$tmp"
      exit 1
    fi
    echo "no new findings"
    ;;
  *)
    echo "Usage: $0 record|check" >&2
    exit 2
    ;;
esac

How the Baseline Works

  • findings runs lint.sh in gcc format, keeps the full report in a temporary file for display, and reduces each line to file code with sed -E. Line and column numbers are dropped on purpose: inserting a line at the top of a file would otherwise make every old finding below it look new.
  • The keys are sorted with LC_ALL=C, because comm requires sorted input and the sort order must be the same on every machine.
  • comm compares the two sorted lists. comm -13 prints lines only in the current list (new findings), comm -23 lines only in the baseline (fixed findings). Duplicates count: if the baseline holds two SC2086 entries for a file and the current code has three, one is reported as new.
  • New findings fail the check with status 1; fixed findings are only reported, with a reminder to re-record the baseline so that the improvement cannot be lost again.
  • A broken lint run is not mistaken for a clean one. If lint.sh fails with status 2, findings exits with 2. Because current=$(findings "$tmp") is an assignment whose status is that of the command substitution, set -e stops the script with status 2 as well, instead of comparing an empty list and reporting every old finding as fixed.

Running It

A legacy script with six findings (two SC2164, two SC2086, one SC2006, plus one SC2006 in another file) is recorded once and the baseline file is committed:

$ scripts/lint-baseline.sh record
recorded 6 known finding(s) in .shellcheck-baseline
$ cat .shellcheck-baseline
bin/build SC2006
bin/legacy-rotate SC2006
bin/legacy-rotate SC2086
bin/legacy-rotate SC2086
bin/legacy-rotate SC2164
bin/legacy-rotate SC2164

Adding an unchecked cd $BACKUP_DIR to bin/build fails the check, and only the new problems are shown:

$ scripts/lint-baseline.sh check; echo "status $?"
NEW findings not in the baseline:
  bin/build:3:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
  bin/build:3:4: note: Double quote to prevent globbing and word splitting. [SC2086]
status 1

When the new problem is in a file that already has findings of the same code, the script knows that one more exists but, without line numbers, cannot tell which one. It then lists every line of that file with that code, and the developer recognizes the line just written.

Replacing the backticks in the legacy script passes the check and reports the progress:

$ scripts/lint-baseline.sh check; echo "status $?"
fixed since the baseline (run 'scripts/lint-baseline.sh record' to lock in the progress):
  bin/legacy-rotate SC2006
no new findings
status 0

Over time, the baseline file shrinks to nothing, at which point it can be deleted and CI can switch to the plain scripts/lint.sh check. Two simpler alternatives also work for gradual adoption: start CI with SHELLCHECK_OPTS='-S error' and lower the severity step by step, or check only changed files with lint.sh --changed.

How These Scripts Were Tested

The scripts in this lesson were run with Bash 5.2 and Git in a sample repository, covering every mode of lint.sh, the hook refusing and accepting commits, the annotation converter, the directive check and all baseline cases shown above. ShellCheck itself could not be installed where this lesson was prepared, because the environment had no network access. The tests therefore used a small stand-in program named shellcheck that reports a few fixed patterns in ShellCheck's gcc format and uses ShellCheck's exit statuses. The findings shown follow the format and messages documented in lesson 162; with real ShellCheck, the lists of findings will be longer, because it applies hundreds of checks rather than three.

The next lesson turns from correctness to speed: what makes Bash scripts slow, and how to measure and fix it.

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 ShellCheck in a Development Workflow and get answers drawn from it.

Signed-in readers only.