Unquoted paths break this archive command. Hidden errors and a successful final printf mask the failure. This Bash script debugging and testing workflow finds the cause and adds tests before deployment.
Use a Linux VM or container with Bash 4.0 or newer. bats-core itself supports Bash 3.2 or later, but the bundled test file in this workflow uses mapfile, which needs Bash 4.0 or newer, so that higher minimum governs the whole exercise. The main package commands target Ubuntu 24.04 LTS. The expected output blocks show what each step should print on that setup; trace prefixes, ShellCheck wording, and bats formatting can differ slightly between tool versions, so compare the meaning of your output rather than exact text.
You’ll follow one maintenance script through tracing, strict mode, ShellCheck, and bats-core tests in continuous integration. For function design and reusable error handling, pair this with Advanced Bash Scripting for Linux Sysadmins: Functions, Error Handling, and Reusable Patterns.
| Diagnostic signal | Tool | What it establishes |
|---|---|---|
| Script won’t parse | bash -n | A syntax error exists before execution |
| Paths split into separate arguments | set -x | Expansion changed the intended command |
| Source text differs from executed arguments | set -v | Shows input before expansion |
| Failure disappears behind later success | Strict mode and trap ERR | Exposes an unhandled nonzero status |
| Quoting or status handling looks suspicious | ShellCheck | Finds known source-level bug patterns |
| A fix breaks after another edit | bats-core | Checks behavior against explicit expectations |
Prepare Linux for Bash script debugging and testing
1. Install the command-line tools
You need a regular user account, package-install privileges, and a writable working directory. You won’t need a service, network share, or special hardware.
On Ubuntu 24.04 LTS or Debian with these packages available:
sudo apt update
sudo apt install -y bash shellcheck bats git tar
On a RHEL-family system, check the enabled repositories first:
dnf info bash ShellCheck bats git tar
If all packages are available:
sudo dnf install -y bash ShellCheck bats git tar
RHEL-family package availability depends on the release and enabled repositories. If ShellCheck or bats isn’t found, follow your distribution’s repository policy or the projects’ install instructions. Don’t add an unrelated repository just to silence a package error.
For other install methods, use the official ShellCheck project and bats-core installation documentation.
Check what actually installed:
bash --version
shellcheck --version
bats --version
git --version
Each command should print its version without a “command not found” error. Record those versions when checking differences between servers.
Distribution packages can lag upstream. These examples use established features, so they don’t need the newest release. Package installs are convenient, but versions should still match between workstations and CI.
2. Create an isolated maintenance-script project
Run the remaining commands in Bash. Keep the same terminal open unless a step says otherwise.
Warning: Run the lab as your normal user. Only package installation requires elevated privileges.
mkdir -p "$HOME/bash-maintenance-lab"
cd "$HOME/bash-maintenance-lab"
mkdir -p scripts tests examples .githooks .github/workflows
mkdir -p "sandbox/source data" "sandbox/backup data"
printf 'maintenance fixture\n' > "sandbox/source data/example.txt"
git init
Create an ignore file so generated archives and diagnostic logs stay out of Git:
# File: $HOME/bash-maintenance-lab/.gitignore
cat > .gitignore <<'EOF'
sandbox/
*.trace
*.stderr
EOF
Expected result: Git creates a repository, and the fixture contains one text file. Its directory has a space on purpose. That space will expose the script’s quoting bug.
Reproduce the silent archive failure before changing it
3. Write the broken maintenance script
This script represents a small scheduled backup job. It creates an archive and prints a completion message.
# File: $HOME/bash-maintenance-lab/scripts/maintenance.sh
cat > scripts/maintenance.sh <<'EOF'
#!/usr/bin/env bash
backup_directory() {
local src=$1
local dest=$2
local archive=$(printf '%s/daily.tar.gz' "$dest")
mkdir -p "$dest"
tar -czf $archive -C $src .
if [ $? -eq 0 ]; then
printf 'Archive created: %s\n' "$archive"
fi
printf 'Maintenance complete\n'
}
backup_directory "$1" "$2"
EOF
chmod +x scripts/maintenance.sh
cp scripts/maintenance.sh examples/maintenance-broken.sh
The copy keeps the original for comparison. Don’t run it against production paths.
Now execute it:
bash scripts/maintenance.sh \
"$PWD/sandbox/source data" \
"$PWD/sandbox/backup data"
printf 'Exit status: %s\n' "$?"
The function’s last command is the unconditional printf 'Maintenance complete\n', so that line and a final exit status of 0 are the only parts of this run guaranteed by the script’s structure.
What’s not guaranteed is how tar reacts to the split, unquoted arguments. The exact failure, and whether it writes a partial or unexpected file, depends on your tar build and the path contents, and its stderr is discarded by regardless. Treat the output below as the expected shape, not a fixed cross-platform result.
Expected output:
Maintenance complete
Exit status: 0
Check the intended artifact:
if [[ -s "sandbox/backup data/daily.tar.gz" ]]; then
printf 'Expected archive exists\n'
else
printf 'Expected archive is missing or empty\n'
fi
Expected output:
Expected archive is missing or empty
The completion message proves only that printf ran. Bash normally returns the status of the last command executed. Here, that command succeeds.
The script also hides tar‘s error stream with . Those two choices make the result look successful.
4. Check the interpreter and syntax
Start with checks that don’t run the maintenance operation:
head -n 1 scripts/maintenance.sh
bash --version
bash -n scripts/maintenance.sh
printf 'Syntax-check status: %s\n' "$?"
Expected signals:
#!/usr/bin/env bash
Syntax-check status: 0
bash -n checks syntax without running commands. It won’t catch wrong paths, missing commands, or bad quoting that’s still valid syntax.
The shebang selects Bash when you run ./scripts/maintenance.sh. Running sh scripts/maintenance.sh overrides that choice and can break Bash-specific syntax.
For scheduled jobs, use an explicit Bash path checked on that server. #!/usr/bin/env bash depends on PATH.
The GNU Bash manual documents -n and the other execution options used below.
Trace expanded arguments with set -x and a useful PS4
5. Send execution traces to a separate file
Use a subshell so the trace settings don’t stay active in your terminal:
(
umask 077
exec 9> "$PWD/maintenance.trace"
# Single quotes defer expansion until each traced command executes.
export PS4='+ ${BASH_SOURCE[0]:-bash}:${LINENO}:${FUNCNAME[0]:-main}: '
export BASH_XTRACEFD=9
bash -x scripts/maintenance.sh \
"$PWD/sandbox/source data" \
"$PWD/sandbox/backup data"
)
less maintenance.trace
Press q to leave less.
The trace should show tar receiving split paths. Look for separate source and data words where you expected one quoted path.
set -x, or bash -x, prints commands after expansion and before execution. The custom PS4 adds the source file, line number, and function name. BASH_XTRACEFD=9 sends the trace to file descriptor 9. That keeps it separate from ordinary errors.
These variables are documented in the Bash reference manual.
Warning: Traces can expose passwords, tokens, and expanded command arguments. Restricted file permissions help, but you still need to control what gets traced.
To keep a credential out of an otherwise traced block, switch tracing off around that one command and back on afterwards:
{ set +x; } 9>/dev/null
curl --fail --silent --netrc-file "$HOME/.netrc-backup" "$upload_url"
set -x
Bash writes the trace line for set +x before tracing turns off, and it writes it to whatever descriptor BASH_XTRACEFD names. In the step 5 setup that’s descriptor 9, not standard error, so the brace group redirects both 2 and 9 to /dev/null to hide that one line. If you don’t use BASH_XTRACEFD, the part alone does the job. Because tracing is already off when curl runs, the command that reads the credential file never appears in the trace.
The descriptor belongs to the subshell and closes when it exits. Avoid setting BASH_XTRACEFD=2 and then unsetting it. Bash closes the descriptor tied to that variable.
6. Compare raw source with expanded commands
Run verbose mode separately:
bash -v scripts/maintenance.sh \
"$PWD/sandbox/source data" \
"$PWD/sandbox/backup data" \
2> maintenance.verbose.stderr
less maintenance.verbose.stderr
-v prints source lines as Bash reads them. You’ll see $archive and $src in their original form. The -x trace shows what those expansions became.
For a long script, limit tracing to the suspect operation:
(
set -x
printf 'Inspecting path: %s\n' "$PWD/sandbox/source data"
set +x
printf 'Tracing is now disabled\n'
)
Only the commands between set -x and set +x are traced. I’d skip full-script tracing once you’ve found the failing block. It adds noise and exposes more data.
Make unhandled failures visible with strict mode and traps
7. Rerun the broken script with strict options
Apply the options from the command line before editing the script:
bash -Eeuo pipefail scripts/maintenance.sh \
"$PWD/sandbox/source data" \
"$PWD/sandbox/backup data"
printf 'Strict-run status: %s\n' "$?"
Expected result: the script exits nonzero before printing Maintenance complete.
The original tar error is still hidden. Strict mode exposes the failure status, but it doesn’t restore redirected error messages.
| Option | What it catches | Important limit |
|---|---|---|
-e | Unhandled nonzero command statuses | Conditional contexts suppress it |
-u | Expansion of unset variables | Empty variables remain valid |
pipefail | Failures before the last pipeline command | Expected nonzero statuses still need handling |
-E | Inherits ERR traps into functions, command substitutions, and subshell environments | It doesn’t enable -e or remove its exceptions |
Read the official set documentation before treating -e as a general exception system.
These details matter in maintenance scripts:
- Commands tested by
if,while, oruntilcan fail on purpose. - Commands in most positions of
&&and||lists don’t trigger-e. - Calling a function as an
ifcondition can suppress-ethroughout its body. ! commandinverts the status and changes error handling.- Command substitutions normally clear
-e, unless settings such asinherit_errexitchange that behavior. local result=$(command)can hide the substitution’s status behindlocal.((count++))returns nonzero when its expression evaluates to zero.
Handle expected failures explicitly. Keep unexpected failures visible.
8. Add an ERR handler that prints the call stack
Create a diagnostic wrapper around the original script:
# File: $HOME/bash-maintenance-lab/examples/diagnose.sh
cat > examples/diagnose.sh <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
report_error() {
trap - ERR
local status=$1
local command=$2
local frame
printf 'ERROR status=%s command=%s\n' "$status" "$command" >&2
for ((frame = 0; frame < ${#FUNCNAME[@]} - 1; frame++)); do
printf ' at %s:%s in %s\n' \
"${BASH_SOURCE[frame + 1]}" \
"${BASH_LINENO[frame]}" \
"${FUNCNAME[frame + 1]}" >&2
done
exit "$status"
}
trap 'report_error "$?" "$BASH_COMMAND"' ERR
# The sourced script reads $1 and $2 at top level, and set -u would abort
# on a missing argument before the diagnostic path runs. Check them first.
if (( $# != 2 )); then
printf 'usage: %s SOURCE_DIR DEST_DIR\n' "${0##*/}" >&2
exit 64
fi
# shellcheck source=scripts/maintenance.sh
source "$PWD/scripts/maintenance.sh" "$1" "$2"
EOF
bash examples/diagnose.sh \
"$PWD/sandbox/source data" \
"$PWD/sandbox/backup data"
printf 'Diagnostic status: %s\n' "$?"
Expected result, when you pass both directory arguments exactly as shown: an error report names the failed tar command and its location inside backup_directory. The argument check matters because the wrapper turns on set -u before sourcing; without both arguments, the sourced script’s top-level $1/$2 would stop it with an unbound-variable error instead, and that error doesn’t go through the ERR trap.
This works here because the script, in its current unfixed form, still ends with an unconditional call to backup_directory "$1" "$2". Sourcing the file runs that call as a side effect of loading it, not as a controlled invocation.
That isn’t a general pattern for reusable modules. Section 11 adds a direct-execution guard so the same file can be sourced for its functions alone, without also triggering main. Until then, treat this wrapper as a diagnostic step tied to the script’s current shape rather than a template for sourcing arbitrary scripts.
BASH_LINENO contains call-site line numbers. FUNCNAME and BASH_SOURCE supply the matching functions and files. The handler walks those arrays together. Its first line, trap - ERR, clears the trap before anything else runs, so a failure inside the handler or its final exit can’t re-enter it and print a second, confusing report.
An ERR trap follows many of the same exceptions as -e. It won’t report every false test. Unset-variable expansion errors and syntax errors also need their own diagnostics.
The Bash manual documents the stack arrays and trap inheritance.
9. Use DEBUG and caller for a short inspection
For a compact command-by-command probe:
bash <<'EOF'
set -T
trap 'printf "DEBUG %s:%s %s\n" "${BASH_SOURCE[0]:-stdin}" "$LINENO" "$BASH_COMMAND" >&2' DEBUG
probe() {
caller 0
printf 'Probe reached\n'
}
probe
trap - DEBUG
EOF
Expected result: DEBUG messages appear before commands, followed by a stack frame from caller 0.
set -T enables function tracing, including DEBUG trap inheritance. caller 0 reports the immediate calling frame when a frame exists. See the Bash builtins reference.
This probe logs each command; it doesn’t pause. For interactive stepping, a DEBUG handler can use read, but only when input comes from a terminal. Don’t put that handler in cron or CI. It can wait forever for someone who isn’t there.
Fix ShellCheck warnings in the maintenance script
10. Read the SC codes before suppressing anything
Run ShellCheck against the broken script:
shellcheck scripts/maintenance.sh
Expect diagnostics including these codes; treat the table as the codes to look for rather than a guaranteed exact list. ShellCheck’s exact messages and the set of codes it reports can vary between releases, so note the shellcheck --version output alongside your results:
| Code | Problem in this script | Repair |
|---|---|---|
SC2086 | Unquoted $archive and $src allow splitting and globbing | Quote each expansion |
SC2155 | local archive=$(...) combines declaration and assignment | Declare first, assign separately |
SC2181 | The script checks $? after tar | Test tar directly with if |
The number names a documented warning pattern. It isn’t a severity score. ShellCheck’s output links to explanations such as SC2086, SC2155, and SC2181.
For SC2155, use:
local archive
archive=$(archive_name "$dest")
The assignment now exposes the substitution’s status. In this example, path generation is unlikely to fail. But combining declaration and assignment becomes dangerous when the substitution runs a real external command.
Separating the two only preserves the status. Under set -e, a failing substitution on that bare assignment line still exits the script (and fires an ERR trap) rather than printing a specific message. To get an explicit diagnostic, test the assignment directly, for example if ! archive=$(archive_name "$dest"); then ... fi.
11. Replace the script with explicit validation and status handling
The corrected version keeps the same job: archive one source directory into daily.tar.gz.
# File: $HOME/bash-maintenance-lab/scripts/maintenance.sh
cat > scripts/maintenance.sh <<'EOF'
#!/usr/bin/env bash
archive_name() {
printf '%s/daily.tar.gz\n' "$1"
}
backup_directory() {
local src=$1
local dest=$2
local archive
local status
if [[ ! -d "$src" ]]; then
printf 'Source directory does not exist: %s\n' "$src" >&2
return 66
fi
if [[ -z "$dest" ]]; then
printf 'Destination must not be empty\n' >&2
return 64
fi
if ! archive=$(archive_name "$dest"); then
printf 'Cannot build archive name for: %s\n' "$dest" >&2
return 70
fi
if mkdir -p -- "$dest"; then
:
else
status=$?
printf 'Cannot create destination: %s\n' "$dest" >&2
return "$status"
fi
if tar -czf "$archive" -C "$src" .; then
printf 'Archive created: %s\n' "$archive"
else
status=$?
printf 'Archive failed: %s\n' "$archive" >&2
return "$status"
fi
}
report_error() {
trap - ERR
local status=$1
local command=$2
local frame
printf 'ERROR status=%s command=%s\n' "$status" "$command" >&2
for ((frame = 0; frame < ${#FUNCNAME[@]} - 1; frame++)); do
printf ' at %s:%s in %s\n' \
"${BASH_SOURCE[frame + 1]}" \
"${BASH_LINENO[frame]}" \
"${FUNCNAME[frame + 1]}" >&2
done
exit "$status"
}
main() {
if [[ $# -ne 2 ]]; then
printf 'Usage: %s SOURCE DESTINATION\n' "${0##*/}" >&2
return 64
fi
backup_directory "$1" "$2"
}
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
set -Eeuo pipefail
trap 'report_error "$?" "$BASH_COMMAND"' ERR
main "$@"
fi
EOF
The direct-execution guard lets tests source functions without running main or changing the caller’s shell options.
Expected failures now get specific messages. The tar status is captured at once inside else, before another command overwrites $?.
The -- after mkdir -p ends option parsing. Quoting keeps each path in one argument.
This remains a teaching backup script. It overwrites the same archive name, lacks locking, and doesn’t publish archives atomically. Use a dedicated backup tool for production retention or backup storage such as Amazon S3 or Backblaze B2.
An explicit if tar ... handles that command’s failure, so ERR doesn’t fire at the tar line. The function prints its own message and returns the failure to the caller. Only if that caller leaves the nonzero return unhandled does the ERR trap fire, and then it reports the call site (the backup_directory call in main), not tar itself. The message names the failed operation; the trap shows the unhandled call path.
12. Add project-wide ShellCheck settings
Create the repository configuration:
# File: $HOME/bash-maintenance-lab/.shellcheckrc
cat > .shellcheckrc <<'EOF'
shell=bash
EOF
bash -n scripts/maintenance.sh
shellcheck scripts/maintenance.sh
printf 'Validation status: %s\n' "$?"
Expected output:
Validation status: 0
Your goal is for both checks to report no diagnostics. This guide doesn’t pin package revisions, and a package update or a different ShellCheck release can add or drop optional warnings, so review anything that appears rather than assuming the fix regressed.
Use inline directives only when you can explain the exception. The diagnostic wrapper’s source= directive tells ShellCheck which file a dynamic source expression loads.
A narrow suppression looks like this:
# Deliberate word splitting for this specific operation.
# shellcheck disable=SC2086
That comment belongs right above the relevant command. Don’t add a repository-wide disable=SC2086 to avoid fixing quotes. ShellCheck supports project settings and directives, but broad exclusions remove useful checks. See the official project documentation.
Write bats-core tests without touching real services
13. Build isolated fixtures and a PATH stub
The tests replace tar with a temporary executable earlier in PATH. They check script behavior without creating archives. This test file needs Bash 4.0 or later, since one check uses mapfile; bats-core’s own compatibility with Bash 3.2 doesn’t extend to this specific file.
# File: $HOME/bash-maintenance-lab/tests/maintenance.bats
cat > tests/maintenance.bats <<'EOF'
#!/usr/bin/env bats
setup() {
PROJECT_ROOT="$(cd "$BATS_TEST_DIRNAME/.." && pwd)"
SCRIPT="$PROJECT_ROOT/scripts/maintenance.sh"
WORKDIR="$(mktemp -d)"
export WORKDIR
mkdir -p "$WORKDIR/bin" "$WORKDIR/source data"
printf 'test fixture\n' > "$WORKDIR/source data/example.txt"
export TAR_ARGS_FILE="$WORKDIR/tar.args"
export TAR_EXIT_STATUS=0
cat > "$WORKDIR/bin/tar" <<'STUB'
#!/usr/bin/env bash
printf '%s\n' "$@" > "$TAR_ARGS_FILE"
exit "${TAR_EXIT_STATUS:-0}"
STUB
chmod +x "$WORKDIR/bin/tar"
export PATH="$WORKDIR/bin:$PATH"
}
teardown() {
# WORKDIR is a fresh mktemp directory owned by this test.
if [[ -n ${WORKDIR:-} && -d "$WORKDIR" ]]; then
rm -rf -- "$WORKDIR"
fi
}
@test "archive_name can be sourced without running main" {
run bash -c '
source "$1"
archive_name "$2"
' _ "$SCRIPT" "$WORKDIR/backup data"
[ "$status" -eq 0 ]
[ "$output" = "$WORKDIR/backup data/daily.tar.gz" ]
}
@test "paths containing spaces reach tar as single arguments" {
run bash "$SCRIPT" "$WORKDIR/source data" "$WORKDIR/backup data"
[ "$status" -eq 0 ]
[ "$output" = "Archive created: $WORKDIR/backup data/daily.tar.gz" ]
mapfile -t args < "$TAR_ARGS_FILE"
[ "${#args[@]}" -eq 5 ]
[ "${args[0]}" = "-czf" ]
[ "${args[1]}" = "$WORKDIR/backup data/daily.tar.gz" ]
[ "${args[2]}" = "-C" ]
[ "${args[3]}" = "$WORKDIR/source data" ]
[ "${args[4]}" = "." ]
}
@test "tar failure returns its status and reports the operation" {
export TAR_EXIT_STATUS=2
run bash "$SCRIPT" "$WORKDIR/source data" "$WORKDIR/backup data"
[ "$status" -eq 2 ]
[[ "$output" == *"Archive failed:"* ]]
[[ "$output" != *"Archive created:"* ]]
}
@test "missing source fails before tar runs" {
run bash "$SCRIPT" "$WORKDIR/missing" "$WORKDIR/backup data"
[ "$status" -eq 66 ]
[[ "$output" == *"Source directory does not exist:"* ]]
[ ! -e "$TAR_ARGS_FILE" ]
}
@test "empty destination is rejected before tar runs" {
run bash "$SCRIPT" "$WORKDIR/source data" ""
[ "$status" -eq 64 ]
[[ "$output" == *"Destination must not be empty"* ]]
[ ! -e "$TAR_ARGS_FILE" ]
}
@test "missing arguments produce usage and status 64" {
run bash "$SCRIPT"
[ "$status" -eq 64 ]
[[ "$output" == *"Usage:"* ]]
[ ! -e "$TAR_ARGS_FILE" ]
}
EOF
Warning: The teardown command deletes each test’s temporary directory. Keep that path tied to
mktemp; don’t replace it with a shared directory.
setup() runs before each test. teardown() removes its fixture afterward.
The bats run helper captures a command’s status in $status and, by default, its combined stdout and stderr in $output. That default is why the failure-message assertions work even though the script writes errors to stderr. If you call run --separate-stderr (bats-core 1.5 or later), stderr moves to $stderr and those assertions would need updating. It runs the command in a subshell. Variable changes inside that command won’t persist in the test.
The stub records arguments in a file because files stay available after run finishes. You can set its exit status to force a failure without breaking a real archive operation.
The bats-core documentation covers these helpers and lifecycle functions.
14. Run the tests and inspect the result
bats --tap tests/maintenance.bats
Expected result with the test file as written (TAP formatting details can vary between bats-core releases, so compare test names and ok/not ok status rather than exact spacing):
1..6
ok 1 archive_name can be sourced without running main
ok 2 paths containing spaces reach tar as single arguments
ok 3 tar failure returns its status and reports the operation
ok 4 missing source fails before tar runs
ok 5 empty destination is rejected before tar runs
ok 6 missing arguments produce usage and status 64
The quoting test checks the argument count and each path. A status-only test would miss a script that reports success while passing broken arguments.
PATH stubs have limits. An absolute command such as /usr/bin/tar bypasses them. Shell builtins and functions also take precedence over PATH lookup.
The run helper doesn’t provide isolation or a timeout by itself. Stub external dependencies and avoid interactive prompts. Use disposable environments for scripts with destructive operations.
15. Verify a real archive separately
Unit tests check the script’s decisions and argument handling. Run a small integration check with the real tar from your normal shell:
bash scripts/maintenance.sh \
"$PWD/sandbox/source data" \
"$PWD/sandbox/backup data"
tar -tzf "$PWD/sandbox/backup data/daily.tar.gz"
Expected archive listing:
./
./example.txt
The first command should also print the archive path. It’s a full path here only because the walkthrough passes an absolute destination; a relative destination prints a relative path.
This check adds evidence the stubbed tests can’t supply. A fake tar can’t prove that a real archive is readable. For valuable data, add restore checks before relying on any backup destination.
Run syntax checks, ShellCheck, and bats before each commit
16. Create one shared verification command
# File: $HOME/bash-maintenance-lab/scripts/check.sh
cat > scripts/check.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
project_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_root"
bash -n scripts/maintenance.sh scripts/check.sh .githooks/pre-commit
shellcheck scripts/maintenance.sh scripts/check.sh .githooks/pre-commit
bats --tap tests/maintenance.bats
EOF
The broken example is excluded on purpose. Including it would make linting fail forever over the bug you’ve kept for comparison.
Create a versioned Git hook:
# File: $HOME/bash-maintenance-lab/.githooks/pre-commit
cat > .githooks/pre-commit <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
project_root="$(git rev-parse --show-toplevel)"
exec bash "$project_root/scripts/check.sh"
EOF
chmod +x scripts/check.sh .githooks/pre-commit
git config --local core.hooksPath .githooks
bash scripts/check.sh
Expected result: syntax and lint checks stay silent, then all six tests pass.
The hook checks working-tree files. It doesn’t isolate staged changes. Avoid partially staging script edits unless you also check the exact staged version.
Git hooks are local settings and can be bypassed. CI supplies a separate check. See Git’s hook documentation.
Add the same Bash checks to GitHub Actions
17. Write a terminal-managed CI workflow
Create the workflow file locally:
# File: $HOME/bash-maintenance-lab/.github/workflows/bash-checks.yml
cat > .github/workflows/bash-checks.yml <<'EOF'
name: Bash checks
on:
push:
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- name: Install ShellCheck and bats-core
run: |
sudo apt-get update
sudo apt-get install -y shellcheck bats
- name: Print tool versions
run: |
bash --version
shellcheck --version
bats --version
- name: Run syntax, lint, and unit tests
run: bash scripts/check.sh
EOF
git add .gitignore .shellcheckrc scripts tests examples .githooks .github
git status --short
Expected result: Git lists the new project files. The ignored sandbox and trace files shouldn’t appear.
If this repository already has a GitHub remote, commit and push through your normal branch workflow:
git commit -m "Add Bash maintenance checks and isolated tests"
git push
A new repository needs a remote and upstream branch configured before git push works. Use your existing repository process rather than pasting an unrelated URL.
GitHub Actions runs the same scripts/check.sh command (not necessarily the same tool versions) on pushes and pull requests. A nonzero status fails the job. The timeout limits how long a hung job runs, but it doesn’t replace correct mocking.
See the official GitHub Actions workflow syntax for triggers, permissions, and job limits.
The fixed Ubuntu runner label reduces operating-system drift, but installed package versions can still change. The version-printing step records that change. For more repeatable builds, use an approved pinned tool image. Pin action dependencies according to your repository policy.
Diagnose remaining Bash failures by their signal
Use the table in order: parsing, expansion, status handling, then test isolation.
| Symptom | Likely cause | Debug technique or fix |
|---|---|---|
syntax error near unexpected token | Invalid syntax or execution through the wrong shell | Run bash -n scripts/maintenance.sh, then inspect the shebang |
| Completion message appears but archive is absent | A later successful command masks failure | Trace with bash -x; check the artifact separately |
| Paths containing spaces fail | Unquoted expansions split arguments | Inspect the trace and fix SC2086 |
set -e doesn’t stop a failing function | Function runs in a conditional context | Inspect its caller; check important statuses explicitly |
ERR trap doesn’t run | Failure is handled, inverted, or occurs before the trap exists | Install the trap first; inspect if, !, and list contexts |
unbound variable | A required value is unset | Validate arguments or use a deliberate default |
| Script works manually but fails in cron | Different PATH, working directory, or environment | Capture a restricted trace and use explicit paths |
| bats hangs | An external command waits for input or a service | Stub that dependency; run alone doesn’t prevent blocking |
| Stub never records arguments | Script uses an absolute executable path or overrides PATH | Inspect the invoked command and dependency lookup |
| Local checks pass but CI fails | Different tools, missing fixtures, or uncommitted files | Compare printed versions and inspect git status --short |
For cron-like environment differences, run a reduced-environment check against the fixture:
env -i \
HOME="$HOME" \
PATH=/usr/bin:/bin \
/bin/bash "$PWD/scripts/maintenance.sh" \
"$PWD/sandbox/source data" \
"$PWD/sandbox/backup data"
Expected result: the corrected script still creates its archive. If it fails, the error points to a dependency on the interactive environment.
This check is useful, but it doesn’t reproduce cron’s user identity, permissions, or full execution context.
FAQ
Should I leave set -x enabled in scheduled scripts?
No. Enable it for a single diagnostic run or a narrow block, send it to a restricted file, and remove it once you’ve found the fault. Permanent tracing adds noise and can leak arguments.
Does ShellCheck replace bats-core tests? No. ShellCheck flags risky source patterns such as unquoted expansions. Tests confirm that the script behaves as expected for specific inputs, so you need both.
Why didn’t set -e stop my failing function?
Bash ignores set -e inside functions called from an if, while, &&, or || context. Check important statuses explicitly instead of relying on strict mode alone.
Wrapping Up
I’d keep tracing temporary and make syntax checks, ShellCheck, and tests permanent. Strict mode catches useful failures, but explicit status handling and archive checks give stronger evidence.
| Step | Action | Applies To |
|---|---|---|
| Diagnose | Check syntax, then trace expanded arguments | Existing failures |
| Repair | Quote paths and preserve failure statuses | Maintenance scripts |
| Prevent | Run lint and isolated tests locally and in CI | Future changes |
| Verify | Run bash scripts/check.sh after tool updates, then list a real fixture archive | Ongoing maintenance |
After a Bash or package update, rerun the checks and the real archive listing. A passing suite confirms the tested script decisions. A readable fixture archive confirms its actual output.