Testing Error Paths and Exit Codes

Su Suriya Ravichandran Updated 06 Dec 2026
18 min read ·Lesson 187 of 205

Most tests people write for a script check the happy path: correct input goes in, the expected result comes out. But a script spends most of its real life dealing with things that go wrong: a missing file, a typo in an option, a full disk, a server that does not answer. The code that handles these situations is called the script's error paths, and it is the code most likely to be broken, because it runs rarely and nobody notices when it misbehaves until the day it matters.

For a shell script, the most important part of an error path is its exit code (also called exit status). Other programs, cron, CI systems and calling scripts do not read the script's messages; they read the number it returns. A script that prints "ERROR" and then exits with status 0 tells every caller that it succeeded. Testing error paths therefore means checking three things for each failure: the exit code is the documented one, the message goes to standard error and says what went wrong, and the state left behind is safe, with no half-written files and no changes that should not have happened.

This lesson shows how to design exit codes that can be tested, how to provoke each failure on purpose, and how to check status, stderr and leftover state, first with plain Bash and then with Bats (lesson 185).

Exit Codes: A Quick Reference

Every command finishes with a number from 0 to 255. Zero means success; anything else means failure (lesson 116). Some values have fixed meanings that tests regularly encounter:

StatusMeaning
0success
1general failure; also "no match" for grep and "files differ" for diff and cmp
2usage error by convention; grep also uses 2 for real errors such as an unreadable file
124the command was stopped by timeout (lesson 142)
126the file was found but could not be executed (for example, missing execute permission)
127command not found
128 + Nthe command was killed by signal N: 130 for SIGINT (Ctrl+C), 143 for SIGTERM

These values can be observed directly:

nosuchcmd 2>/dev/null; echo "missing command -> $?"
touch notexec; ./notexec 2>/dev/null; echo "not executable -> $?"
timeout 1 sleep 5; echo "timeout -> $?"
sleep 5 & pid=$!; kill -TERM "$pid"; wait "$pid"; echo "killed by TERM -> $?"
grep -q x /nonexistent; echo "grep, missing file -> $?"
echo abc | grep -q x; echo "grep, no match -> $?"
missing command -> 127
not executable -> 126
timeout -> 124
killed by TERM -> 143
grep: /nonexistent: No such file or directory
grep, missing file -> 2
grep, no match -> 1

Notice how grep distinguishes "nothing found" (1) from "something is broken" (2). Good scripts make the same kind of distinction, and tests make sure the distinction survives future changes.

Values Outside 0 to 255

An exit status is stored in 8 bits, so Bash keeps only the remainder after dividing by 256. A script that computes its exit code, for example by counting errors, can accidentally report success:

bash -c 'exit 256'; echo "exit 256 -> $?"
bash -c 'exit 300'; echo "exit 300 -> $?"
bash -c 'exit -1';  echo "exit -1 -> $?"
exit 256 -> 0
exit 300 -> 44
exit -1 -> 255

A script that runs exit "$error_count" returns 0 after exactly 256 errors. Cap such values, for example with (( error_count > 0 )) && exit 1, and test the boundary if the code computes its status.

Designing Exit Codes That Can Be Tested

Before an error path can be tested, the script must say what it promises. The script used in this lesson validates a CSV sales report and publishes it into a directory. Its header comment documents one exit code per kind of failure:

#!/usr/bin/env bash
#
# publish-report.sh - validate a CSV sales report and publish it into a directory
#
# Usage: publish-report.sh [-f] REPORT.csv DEST_DIR
#
# Exit status:
#   0  report published
#   2  usage error (wrong number of arguments or unknown option)
#   3  report missing or unreadable
#   4  report invalid (wrong header or no data rows)
#   5  destination not writable, or copying failed
#   6  report already published (use -f to replace it)

set -euo pipefail

readonly EX_USAGE=2 EX_NOINPUT=3 EX_DATAERR=4 EX_CANTCREAT=5 EX_EXISTS=6
readonly HEADER='date,region,amount'

die() {
  local code=$1
  shift
  printf '%s: %s\n' "${0##*/}" "$*" >&2
  exit "$code"
}

usage() { printf 'Usage: %s [-f] REPORT.csv DEST_DIR\n' "${0##*/}" >&2; }

force=0
while getopts ':f' opt; do
  case $opt in
    f) force=1 ;;
    *) usage; exit "$EX_USAGE" ;;
  esac
done
shift $((OPTIND - 1))
(( $# == 2 )) || { usage; exit "$EX_USAGE"; }
report=$1 dest=$2

[[ -f $report && -r $report ]] || die "$EX_NOINPUT" "cannot read report: $report"

first=""
IFS= read -r first < "$report" || true        # an empty file has no first line
[[ $first == "$HEADER" ]] || die "$EX_DATAERR" "bad header in $report (expected '$HEADER')"
rows=$(( $(wc -l < "$report") - 1 ))
(( rows > 0 )) || die "$EX_DATAERR" "no data rows in $report"

[[ -d $dest && -w $dest ]] || die "$EX_CANTCREAT" "destination not writable: $dest"
target=$dest/${report##*/}
if [[ -e $target ]] && (( ! force )); then
  die "$EX_EXISTS" "already published: $target (use -f to replace it)"
fi

tmp=$(mktemp "$dest/.publish.XXXXXX") || die "$EX_CANTCREAT" "cannot create a temporary file in $dest"
trap 'rm -f "$tmp"' EXIT                      # never leave a half-written file behind
cp -- "$report" "$tmp" || die "$EX_CANTCREAT" "copy failed: $report -> $tmp"
mv -f -- "$tmp" "$target" || die "$EX_CANTCREAT" "cannot move the report into place: $target"
trap - EXIT

printf 'published %s (%d rows)\n' "$target" "$rows"

Several design choices make this script easy to test:

  • Named constants for exit codes. EX_USAGE, EX_NOINPUT and the others make every exit self-explanatory and keep the numbers in one place. The names follow the style of the traditional BSD sysexits.h codes, but the values here are the script's own, chosen to be small and documented. What matters is that they are distinct and written down.
  • One die function. Every failure goes through die, which prints scriptname: message to standard error and exits with the given code. Tests can rely on a single message format.
  • Messages on stderr, results on stdout. A caller that captures the script's output receives only the success message, never an error mixed into data.
  • Write to a temporary file, then rename. The report is copied to a temporary file in the destination directory and moved into place only when the copy succeeded. A trap ... EXIT (lesson 124) deletes the temporary file on every failure. The visible result is all or nothing, which is exactly what a test can check.
  • Explicit handling of the empty file. read fails at end of file, which would stop a set -e script with status 1 and no message. || true turns that into the documented status 4.

Running it by hand shows the contract in action:

$ ./bin/publish-report.sh; echo "status $?"
Usage: publish-report.sh [-f] REPORT.csv DEST_DIR
status 2
$ printf 'day;x\n' > /tmp/bad.csv
$ ./bin/publish-report.sh /tmp/bad.csv /tmp; echo "status $?"
publish-report.sh: bad header in /tmp/bad.csv (expected 'date,region,amount')
status 4

Capturing Exit Codes Correctly

Testing exit codes in Bash is easy to get subtly wrong, because $? is fragile. It always holds the status of the most recent command, so it must be read immediately. Four traps catch people regularly.

Anything in between overwrites $?. An echo or [ ... ] placed between the command and the check reports its own status instead. Save it right away:

"$PUBLISH" "$report" "$dir"
status=$?                         # the very next command

A pipeline reports its last command. cmd | tee log returns the status of tee, which almost always succeeds. PIPESTATUS holds every element's status, and set -o pipefail makes the pipeline fail when any part fails (lesson 120):

false | true; echo "false | true -> $?"
false | true; echo "PIPESTATUS: ${PIPESTATUS[*]}"
false | true -> 0
PIPESTATUS: 1 0

local hides the status of a command substitution. local x=$(cmd) returns the status of local, which is 0. Declare first, assign second:

f() { local x=$(false); echo "local masked -> $?"; }; f
g() { local x; x=$(false); echo "separate -> $?"; }; g
local masked -> 0
separate -> 1

! turns any failure into success. ! cmd is useful for "this must fail", but it cannot distinguish status 2 from status 4. An error-path test that only checks "it failed" passes even when the script fails for the wrong reason, for instance with 127 because a command was misspelled. Check the exact code whenever the script documents one.

set -e adds one more complication: in a test script with set -e, a failing command under test would stop the whole test before its status could be checked. Either leave set -e off in the test driver, or run the command where set -e does not apply, such as in an if condition or with || status=$?.

Testing Error Paths with Plain Bash

A test framework is convenient but not required. A small function that runs a command, saves $? and compares it with the expected value is enough for a smoke test that can run anywhere:

#!/usr/bin/env bash
# smoke.sh - check the exit statuses of publish-report.sh without any test framework

PUBLISH=${PUBLISH:-./bin/publish-report.sh}
failures=0

# expect_status WANT DESCRIPTION -- COMMAND...
expect_status() {
  local want=$1 desc=$2 got
  shift 3                       # drop WANT, DESCRIPTION and the -- separator
  "$@" > /dev/null 2>&1
  got=$?                        # read $? immediately, before anything else runs
  if (( got == want )); then
    printf 'PASS  %-34s status %d\n' "$desc" "$got"
  else
    printf 'FAIL  %-34s expected %d, got %d\n' "$desc" "$want" "$got"
    failures=$((failures + 1))
  fi
}

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir "$work/out"
printf 'date,region,amount\n2026-11-30,south,1250\n' > "$work/ok.csv"
printf 'date,region,amount\n'                        > "$work/empty.csv"

expect_status 2 "no arguments"            -- "$PUBLISH"
expect_status 3 "missing report"          -- "$PUBLISH" "$work/missing.csv" "$work/out"
expect_status 4 "header only"             -- "$PUBLISH" "$work/empty.csv" "$work/out"
expect_status 5 "destination is a file"   -- "$PUBLISH" "$work/ok.csv" "$work/ok.csv"
expect_status 0 "valid report"            -- "$PUBLISH" "$work/ok.csv" "$work/out"
expect_status 6 "second publish refused"  -- "$PUBLISH" "$work/ok.csv" "$work/out"

(( failures == 0 )) || { echo "$failures check(s) failed"; exit 1; }
echo "all checks passed"
$ ./test/smoke.sh
PASS  no arguments                       status 2
PASS  missing report                     status 3
PASS  header only                        status 4
PASS  destination is a file              status 5
PASS  valid report                       status 0
PASS  second publish refused             status 6
all checks passed

How it works:

  • The -- separator makes calls easy to read: everything after it is the command. shift 3 removes the expected status, the description and the separator, leaving the command in "$@", which runs it with all arguments preserved.
  • got=$? comes directly after the command, as discussed above. The script deliberately does not use set -e, because the commands under test are supposed to fail.
  • Every test case uses its own scratch directory created with mktemp -d and removed by a trap, so the tests never touch real data.
  • The last two checks depend on each other: the first publish succeeds and the second must then fail with status 6. Ordering like this is acceptable in a short smoke test; in a larger suite, each test should create its own state, as the Bats version below does.
  • The smoke test itself exits non-zero when any check fails, so a CI system (lesson 177) can run it like any other command.

To see that the test protects the contract, change the script's "no data rows" error from die "$EX_DATAERR" to die 1, a typical refactoring slip. The message is still correct, but the smoke test notices the wrong code:

$ PUBLISH=/tmp/mutated-publish-report.sh ./test/smoke.sh
PASS  no arguments                       status 2
PASS  missing report                     status 3
FAIL  header only                        expected 4, got 1
PASS  destination is a file              status 5
PASS  valid report                       status 0
PASS  second publish refused             status 6
1 check(s) failed

Testing Error Paths with Bats

Bats makes error-path tests shorter and adds the ability to check standard output and standard error separately. Two features of its run command are made for this lesson's topic (they require Bats 1.5.0 or later, which is why the file starts with bats_require_minimum_version 1.5.0):

  • run -N command fails the test unless the command exits with exactly status N. run -0 demands success; run ! demands any non-zero status.
  • run --separate-stderr command puts standard output in $output and standard error in $stderr. Without it, both streams are mixed in $output, which hides a script that prints errors on the wrong stream.

The complete test file covers every documented exit code:

#!/usr/bin/env bats
#
# Error-path tests for bin/publish-report.sh: every documented exit status,
# the message on stderr, and the state of the destination afterwards.

bats_require_minimum_version 1.5.0

setup() {
  PUBLISH="$BATS_TEST_DIRNAME/../bin/publish-report.sh"
  SRC="$BATS_TEST_TMPDIR/sales.csv"
  OUT="$BATS_TEST_TMPDIR/public"
  mkdir "$OUT"
  printf 'date,region,amount\n2026-11-30,south,1250\n2026-11-30,north,980\n' > "$SRC"
}

# --- usage errors: status 2 -------------------------------------------------

@test "no arguments: status 2, usage on stderr, nothing on stdout" {
  run -2 --separate-stderr "$PUBLISH"
  [ -z "$output" ]
  [[ $stderr == "Usage: publish-report.sh [-f] REPORT.csv DEST_DIR" ]]
}

@test "unknown option: status 2" {
  run -2 --separate-stderr "$PUBLISH" -x "$SRC" "$OUT"
  [[ $stderr == Usage:* ]]
}

# --- input errors: status 3 and 4 ------------------------------------------

@test "missing report: status 3 with the file name in the message" {
  run -3 --separate-stderr "$PUBLISH" "$BATS_TEST_TMPDIR/nope.csv" "$OUT"
  [ "$stderr" = "publish-report.sh: cannot read report: $BATS_TEST_TMPDIR/nope.csv" ]
}

@test "unreadable report: status 3" {
  [[ $EUID -ne 0 ]] || skip "root can read any file"
  chmod 000 "$SRC"
  run -3 "$PUBLISH" "$SRC" "$OUT"
}

@test "wrong header: status 4" {
  printf 'day;region;amount\n2026-11-30;south;1250\n' > "$SRC"
  run -4 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
  [[ $stderr == *"bad header"* ]]
}

@test "header without data rows: status 4" {
  printf 'date,region,amount\n' > "$SRC"
  run -4 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
  [[ $stderr == *"no data rows"* ]]
}

@test "empty file: status 4, not a crash" {
  : > "$SRC"
  run -4 "$PUBLISH" "$SRC" "$OUT"
}

# --- destination errors: status 5 and 6 ------------------------------------

@test "destination is a file, not a directory: status 5" {
  run -5 "$PUBLISH" "$SRC" "$SRC"
  [[ $output == *"destination not writable"* ]]
}

@test "read-only destination: status 5" {
  [[ $EUID -ne 0 ]] || skip "root can write to read-only directories"
  chmod 555 "$OUT"
  run -5 "$PUBLISH" "$SRC" "$OUT"
}

@test "already published: status 6 and the old copy is untouched" {
  echo "old version" > "$OUT/sales.csv"
  run -6 "$PUBLISH" "$SRC" "$OUT"
  [ "$(cat "$OUT/sales.csv")" = "old version" ]
}

@test "-f replaces an existing copy: status 0" {
  echo "old version" > "$OUT/sales.csv"
  run -0 "$PUBLISH" -f "$SRC" "$OUT"
  cmp -s "$SRC" "$OUT/sales.csv"
}

@test "failed copy: status 5, no target and no temporary file left behind" {
  load mocks
  mock_setup
  mock cp 1
  run -5 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
  [[ $stderr == *"copy failed"* ]]
  [ ! -e "$OUT/sales.csv" ]
  [ -z "$(ls -A "$OUT")" ]
}

# --- the success path, for contrast ----------------------------------------

@test "valid report: status 0, message on stdout, stderr empty" {
  run -0 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
  [ "$output" = "published $OUT/sales.csv (2 rows)" ]
  [ -z "$stderr" ]
  cmp -s "$SRC" "$OUT/sales.csv"
}

How the Tests Provoke Each Failure

Every error path needs a way to make it happen on demand. The test file uses four techniques, which together cover most real scripts:

  1. Bad arguments. Calling the script with too few arguments or an unknown option is the simplest failure to provoke, and the usage path is one of the most frequently broken.
  2. Crafted input files. Each test writes exactly the content it needs into $BATS_TEST_TMPDIR: a wrong header, a header with no rows, an empty file. Boundary cases like the empty file are where scripts most often crash instead of failing cleanly.
  3. Manipulated file system state. A destination that is a regular file, a file that already exists, or permissions removed with chmod.
  4. Fake commands. Some failures cannot be produced with files alone. A copy that fails halfway through, for example because the disk filled up, is hard to arrange for real. The test uses the mock library from lesson 186 to replace cp with a fake that exits with status 1, which drives the script into its cleanup code.

Permissions and the Root User

The tests for an unreadable report and a read-only destination are skipped when the tests run as root. The superuser ignores ordinary read and write permissions, so chmod 000 does not make a file unreadable for root, and the script would correctly succeed. Without the skip, these tests would fail in Docker containers and CI jobs that run as root, for reasons that have nothing to do with the script. Bats reports skipped tests separately, so they remain visible:

ok 4 unreadable report: status 3 # skip (root can read any file)

When the same suite runs as an ordinary user, both tests execute and pass. If permission paths matter, run the suite at least once as a non-root user, for instance with runuser -u nobody in a container.

Checking the State Left Behind

The status code alone does not prove that an error path is safe. Three tests check the file system after the failure:

  • "already published" verifies that the existing copy still says old version. A script that refused with status 6 but had already overwritten the file would pass a status-only test.
  • "failed copy" verifies that the target does not exist and that ls -A "$OUT" prints nothing, which means no hidden .publish.XXXXXX file remains. This is the test that guards the trap cleanup.
  • "valid report", the success test, uses cmp -s to prove that the published file is byte-for-byte identical to the source.

Running the Suite

As in lessons 185 and 186, Bats could not be installed where this lesson was prepared, because the environment had no network access. The tests were executed with Bash 5.2 using a small stand-in harness that implements the Bats features used here (run -N, run !, --separate-stderr, skip, load, setup) and prints TAP output in the format of bats --tap. The run was done as root, so the two permission tests were skipped; a second run as the unprivileged user nobody executed and passed them.

$ bats --tap test/publish-report.bats
1..13
ok 1 no arguments: status 2, usage on stderr, nothing on stdout
ok 2 unknown option: status 2
ok 3 missing report: status 3 with the file name in the message
ok 4 unreadable report: status 3 # skip (root can read any file)
ok 5 wrong header: status 4
ok 6 header without data rows: status 4
ok 7 empty file: status 4, not a crash
ok 8 destination is a file, not a directory: status 5
ok 9 read-only destination: status 5 # skip (root can write to read-only directories)
ok 10 already published: status 6 and the old copy is untouched
ok 11 -f replaces an existing copy: status 0
ok 12 failed copy: status 5, no target and no temporary file left behind
ok 13 valid report: status 0, message on stdout, stderr empty

To confirm that test 12 really guards the cleanup, the line trap 'rm -f "$tmp"' EXIT was removed from the script. The script still exits with status 5 and prints the right message, so a status-only test would pass. The state check catches the leftover temporary file:

not ok 12 failed copy: status 5, no target and no temporary file left behind
# (in test file test/publish-report.bats, line 91)
#   `[ -z "$(ls -A "$OUT")" ]' failed

Testing Signals and Timeouts

Scripts that run for a long time also have error paths triggered from outside: a user presses Ctrl+C, a service manager sends SIGTERM, or a timeout wrapper stops them. The same approach applies. Start the script in the background, send the signal, collect the status with wait, and inspect the state:

./long-job.sh "$workdir" &
pid=$!
sleep 1                      # give the script time to start working
kill -TERM "$pid"
wait "$pid"
status=$?
(( status == 143 ))          # 128 + 15: terminated by SIGTERM
[ -z "$(ls -A "$workdir/tmp")" ]   # the trap removed the temporary files

If the script catches the signal with trap ... TERM and exits on its own, it decides its exit code itself; many scripts deliberately exit with 128 + signal number so that callers can still tell that it was interrupted (lesson 141). Whichever convention the script follows, the test writes it down. Avoid long sleep calls in tests: wait for a file that the script creates when it is ready, or replace sleep with a fake as in lesson 186.

Choosing Which Error Paths to Test

A script usually has more possible failures than are worth a test each. A useful order of priority:

  1. Every documented exit code at least once. If the header comment promises a code, a test should prove it.
  2. Paths that protect data: refusing to overwrite, cleaning up partial output, rolling back. These are the failures whose bugs cause real damage.
  3. Boundary inputs: empty files, a header without rows, a single line without a trailing newline, file names with spaces (lesson 111).
  4. Failures of external commands that the script handles explicitly, provoked with fakes.

The next lesson moves from testing to portability: how to write scripts that behave the same way on different systems and shells, including the systems where the error paths in this lesson were never exercised.

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 Testing Error Paths and Exit Codes and get answers drawn from it.

Signed-in readers only.