Posted on
Artificial Intelligence

Troubleshooting Bash Scripts with Artificial Intelligence

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

Troubleshooting Bash Scripts with Artificial Intelligence

Bash is everywhere: CI pipelines, system automation, quick data wrangling, and production glue. And yet, when a five‑line Bash one‑liner grows into a 500‑line script with mysterious failures, debugging can turn into a time sink. This post shows how to combine the best of two worlds—classic Unix tools and modern AI—to troubleshoot Bash scripts systematically and faster.

You’ll learn a practical workflow, complete with install commands for major distros, real prompts to send to an AI assistant, and example code you can adapt today.


Why bring AI into Bash troubleshooting?

  • Speed: AI can summarize logs, spot anti‑patterns, and generate candidate fixes faster than you can grep.

  • Breadth: It “remembers” lint rules, POSIX quirks, and gotchas in string handling, globbing, and arrays.

  • Teaching: Explanations turn into reusable knowledge for your team.

Caveat: AI can be confidently wrong. Treat it like a pair‑programming partner with great recall but no terminal. Always verify locally with tests and linters.


What you’ll need

We’ll use familiar tools to capture high‑signal context that an AI can reason about. Install these once, then keep them in your toolbox:

  • shellcheck: Lints Bash/sh for bugs and pitfalls

  • jq: JSON processor (for AI API responses)

  • bats: Bash Automated Testing System

  • strace: System call tracer

  • bashdb: Interactive Bash debugger

Install on your distro:

  • Debian/Ubuntu (apt)
sudo apt update && sudo apt install -y shellcheck jq bats strace bashdb
  • Fedora/RHEL (dnf)
sudo dnf install -y ShellCheck jq bats strace bashdb
  • openSUSE (zypper)
sudo zypper install -y ShellCheck jq bats strace bashdb

You’ll also need curl (usually preinstalled). If not:

  • Debian/Ubuntu
sudo apt install -y curl
  • Fedora/RHEL
sudo dnf install -y curl
  • openSUSE
sudo zypper install -y curl

For AI access, you can use any OpenAI‑compatible HTTP API (cloud or local). Set these environment variables to match your provider:

export AI_API_URL="https://your-ai-endpoint.example.com"
export AI_API_KEY="sk-..."

A running example: a flaky log parser

Suppose you have this script:

#!/usr/bin/env bash
# buggy.sh
set -u
input_dir=$1

for f in $(ls "$input_dir"/*.txt); do
  cat $f | grep -i error >> report.txt
done

echo "Done: $(wc -l report.txt) lines"

Symptoms:

  • Crashes if $1 is missing

  • Breaks on file names with spaces/newlines

  • Useless use of cat; unquoted expansions; race conditions on report.txt

Let’s fix it using a repeatable, AI‑assisted workflow.


1) Capture high‑signal context (make failures explainable)

AI does best when you feed it compact, relevant evidence. Add tracing and redaction so you can safely share logs.

  • Turn on strict mode, timestamps, and trace:
# debug_harness.sh
set -Eeuo pipefail
shopt -s lastpipe

# Rich trace prompt: file:line:function
export PS4='+ ${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '

# Write xtrace to a file with timestamps
exec 3>&2
export BASH_XTRACEFD=3
  • Run your script under trace:
# Capture trace and stderr in one place
bash -x buggy.sh "/path/with spaces" 3>trace.raw.log 2>&1 || true
  • Redact secrets before sharing:
sed -E 's/(password|token|secret)=\S+/\1=REDACTED/gi' trace.raw.log > trace.redacted.log
  • Summarize the last failing lines:
tail -n 200 trace.redacted.log > trace.tail.log

Why this helps:

  • set -Eeuo pipefail surfaces failures early.

  • PS4 with file/line/function turns noisy -x into navigable breadcrumbs.

  • Redaction lets you safely paste to an AI tool.


2) Run static analysis first (then ask AI to explain and fix)

Start with shellcheck to catch the low‑hanging bugs:

shellcheck buggy.sh

Typical warnings you’ll see for this script:

  • SC2086: Double quote to prevent globbing and word splitting

  • SC2046/SC2013: Useless use of ls; iterating over command output

  • SC2145: Argument/splitting issues

  • SC2124/SC2154: Unset variables

Now ask an AI assistant to prioritize and propose safe fixes. Here’s a prompt pattern that works well:

cat > prompt.txt <<'EOF'
You are a senior Bash engineer. Diagnose and propose POSIX-safe fixes.
Constraints:

- Explain each fix briefly.

- Prefer built-ins over external commands.

- Handle paths with spaces/newlines.

- Keep behavior identical unless noted.

SCRIPT:
<<<
# paste buggy.sh here
>>>

SHELLCHECK:
<<<
# paste: shellcheck -f gcc buggy.sh
>>>

Goal: Make the script robust and testable.
EOF

Send it to your AI provider and get a readable answer:

curl -sS -H "Authorization: Bearer $AI_API_KEY" \
  -H "Content-Type: application/json" \
  -d @- "$AI_API_URL/v1/chat/completions" <<'JSON' | jq -r '.choices[0].message.content'
{
  "model": "bash-expert",
  "messages": [
    {"role": "system", "content": "You are a Bash expert who writes safe, portable code."},
    {"role": "user", "content": "'"$(sed -e "s/'/'\"'\"'/g" prompt.txt)"'"}
  ],
  "temperature": 0.1
}
JSON

You’ll typically get a revised script with explanations. Verify locally before trusting it.

A robust rewrite might look like:

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s nullglob

input_dir=${1:-}
if [[ -z "${input_dir}" ]]; then
  printf 'Usage: %s <input_dir>\n' "${0##*/}" >&2
  exit 2
fi

: > report.txt  # truncate safely

# Use globbing; handle spaces; avoid UUoC
for f in "$input_dir"/*.txt; do
  grep -i -- 'error' -- "$f" >> report.txt
done

# Quote wc invocation
printf 'Done: %s lines\n' "$(wc -l < report.txt)"

3) Shrink to a repro and add tests (so AI changes are safe)

Turn the bug into a small, testable example. A test harness makes it trivial to confirm (or revert) AI‑generated fixes.

  • Create Bats tests:
# test_buggy.bats
setup() {
  rm -f report.txt
  mkdir -p tmpdir
  printf 'ok\nERROR here\n' > "tmpdir/one file.txt"
  printf 'nothing\n'        > "tmpdir/two.txt"
}

teardown() {
  rm -rf tmpdir report.txt
}

@test "prints usage when missing arg" {
  run ./buggy.sh
  [ "$status" -eq 2 ]
  [[ "$output" == *"Usage:"* ]]
}

@test "greps case-insensitive and handles spaces" {
  run ./buggy.sh "tmpdir"
  [ "$status" -eq 0 ]
  [ -f report.txt ]
  run wc -l < report.txt
  [ "$output" -eq 1 ]
}
  • Run tests:
bats test_buggy.bats
  • Ask AI to suggest more edge cases (empty directory, unreadable file, NUL in names, huge inputs), but keep tests authoritative.

Prompt idea:

Suggest 3 additional Bats test cases that cover edge conditions for this script,
without changing its intended behavior. Show only valid Bats code.
Context:
<<<
# paste script here
>>>

4) Step through and trace what the system sees

When logic looks fine but the environment misbehaves (permissions, PATH, encodings), a debugger and strace shine—and AI can help summarize the noise.

  • Step through with bashdb:
bashdb ./buggy.sh tmpdir
# Examples inside bashdb:
# b 12        # set breakpoint
# s           # step into
# n           # next
# p input_dir # print variable
# where       # backtrace
  • Trace system calls to catch OS‑level failures:
strace -f -o strace.log -e trace=process,file,network ./buggy.sh tmpdir
  • Ask AI to spot anomalies quickly:
printf 'Find missing files, EACCES, ENOENT, and PATH issues in this strace:\n\n%s\n' \
  "$(sed -n '1,200p' strace.log)" | \
curl -sS -H "Authorization: Bearer $AI_API_KEY" \
     -H "Content-Type: application/json" \
     -d @- "$AI_API_URL/v1/chat/completions" | jq -r '.choices[0].message.content'

It will often highlight failing opens, permission errors, or wrong executable paths you missed.


Make AI productive: five prompt tips

  • Be specific about the goal: “Preserve behavior; fix word‑splitting and error handling.”

  • Provide constraints: “POSIX‑ish if possible; no external deps; must pass these tests.”

  • Include context: script, shellcheck output, last 100 lines of -x trace, and error messages.

  • Keep examples small: two failing cases + expected outputs beat a rambling description.

  • Ask for diffs or patch‑style output to apply changes safely.


Common pitfalls and guardrails

  • Don’t paste secrets. Redact variables and tokens first.

  • Verify everything. Lint, run tests, and sanity‑check file permissions and PATH.

  • Prefer minimal changes. Big refactors hide new bugs.

  • Document assumptions (Bash version, OS, encodings); include them in your prompt.


Conclusion and next steps

Troubleshooting Bash with AI isn’t about replacing your Unix skills—it’s about amplifying them. Combine strict tracing, linters, tests, and targeted AI prompts to move from “what on earth is this doing?” to “green tests” quickly and repeatably.

Your next steps: 1) Install the tooling with your package manager of choice. 2) Wrap failing runs with -x and redaction. 3) Pair shellcheck output and a minimal repro with an AI prompt. 4) Verify with Bats, debug with bashdb/strace if needed.

Got a gnarly script? Start by dropping a 20‑line snippet, shellcheck output, and your last 50 lines of trace into a prompt. You’ll be surprised how quickly you get to a clean, test‑backed fix.