Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Testing Bash Scripts Before Combining Them Into One Tool

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

When you build a larger tool from several smaller bash scripts, testing each piece in isolation first saves you from debugging a tangled mess later. This guide walks you through a practical, step-by-step approach to validate individual scripts before merging them, ensuring the final combined tool behaves predictably.

What You'll Need

  • A Linux or macOS environment with Bash (version 4+ recommended).
  • Basic familiarity with the command line and shell scripting.
  • The individual bash scripts you plan to combine.
  • Optional: a test directory where you can safely run experiments.

Step-by-Step

  1. Run each script with `bash -n` to check syntax.
    Before doing anything else, run bash -n script.sh for each script. This parses the script without executing it and reports any syntax errors. If it outputs nothing, the syntax is valid.
  2. Run each script with `bash -x` to trace execution.
    Execute bash -x script.sh to see every command as it runs, with variables expanded. This helps you spot logical errors, wrong variable names, or unexpected control flow. Capture the output with bash -x script.sh > trace.log 2>&1 for later review.
  3. Test with sample inputs and expected outputs.
    Create a small set of test cases that cover normal, edge, and error conditions. For each test case, run the script with the input and compare the output to what you expect. Use diff to compare against a stored expected output file: ./script.sh input.txt | diff - expected_output.txt.
  4. Check exit codes.
    After running a script, echo $? to see its exit status. A non-zero exit code usually indicates an error. Ensure your script returns 0 on success and a specific non-zero code on failure, and test that these are correct.
  5. Test with `set -euo pipefail` in a subshell.
    Run each script with bash -c 'set -euo pipefail; source script.sh' (or run it with these options set at the top temporarily). This makes the script exit on any error, undefined variable, or failed pipeline command, revealing hidden issues that might otherwise be ignored.
  6. Isolate environment dependencies.
    Run each script in a clean environment using env -i PATH=/usr/bin:/bin HOME=$HOME script.sh. This ensures the script doesn't rely on environment variables or aliases that won't be present in the combined tool.
  7. Test for idempotency.
    Run the script twice on the same input. If it modifies files or state, the second run should not produce errors or unexpected changes. This is crucial for scripts that will be called multiple times.
  8. Document each script's interface.
    Write down the inputs, outputs, exit codes, and any side effects for each script. This becomes your contract when combining them. Use comments at the top of each script to summarize this.
  9. Combine scripts incrementally.
    Start by combining two scripts that are most dependent on each other. Test the combination as you would a single script, using the same steps. Then add the next script, and so on, rather than merging everything at once.
  10. Use a test harness for regression testing.
    Once the combined tool is stable, create a simple test script that runs all your test cases automatically. This ensures that future changes don't break existing functionality.

Common Mistakes

  • Skipping syntax checks. A missing quote or parenthesis can cause cryptic errors later. Always run bash -n first.
  • Ignoring exit codes. If a script fails silently, the combined tool may continue with bad data. Always check $?.
  • Testing only the happy path. Edge cases like empty inputs, missing files, or permission issues often reveal bugs.
  • Not isolating environment variables. Scripts that rely on variables set by your shell may break when run from cron or another script.
  • Combining scripts before testing them individually. This makes it nearly impossible to pinpoint which script introduced a bug.
  • Forgetting to test with `set -e`. Without it, a failing command might not stop the script, leading to cascading errors.

Tips

  • Use shellcheck (a static analysis tool) to catch common pitfalls. Install it with your package manager and run shellcheck script.sh.
  • Keep scripts small and focused. A script that does one thing well is easier to test and reuse.
  • Use functions within scripts to break up complex logic, and test each function separately if possible.
  • Use printf instead of echo for more predictable output formatting.
  • When testing, use temporary directories and clean up after yourself. Use trap 'rm -rf "$TMPDIR"' EXIT in your test scripts.
  • Version control your scripts and test cases. This lets you revert to a known good state.

Troubleshooting

If a script fails during testing, follow these steps:

  • Check the error message. Read it carefully; it often points directly to the line number and cause.
  • Run with bash -x to see the exact commands being executed. Look for unexpected variable values or command expansions.
  • Isolate the problematic line. Comment out parts of the script to narrow down where the issue occurs.
  • Check file permissions. Ensure the script is executable (chmod +x script.sh) and that any files it reads/writes have the correct permissions.
  • Check for hidden characters. If you edited the script on Windows, there may be carriage returns (\r). Remove them with sed -i 's/\r$//' script.sh.
  • Verify the environment. Run env | sort to see what variables are set. Compare with what the script expects.
  • If the script works when run manually but not from another script, check the working directory. Use cd "$(dirname "$0")" at the start of the script to ensure it runs from its own location.

Frequently Asked Questions

Can I test a bash script without executing it?

Yes, bash -n script.sh checks syntax without running it. For more thorough static analysis, use shellcheck.

What is the best way to test a script that requires user input?

Use a here-document to provide input: ./script.sh <<EOF input1 input2 EOF. Or use printf 'input\n' | ./script.sh.

How do I test a script that modifies system files?

Run it in a container or a virtual machine, or at least use a test user account. You can also use strace to see what files it touches, but the safest is to test in an isolated environment.

Should I test scripts with `bash script.sh` or `./script.sh`?

Both, but they differ. ./script.sh requires the shebang line and executable permission. bash script.sh uses the Bash interpreter directly. Test both to ensure the shebang is correct.

How do I test a script that takes a long time?

Use smaller sample data or add a timeout command: timeout 10 ./script.sh. Also, consider adding debug output to see progress.

What is the most important test to run before combining scripts?

The most critical is to verify each script's exit codes and error handling. If a script fails silently, the combined tool will produce wrong results without any indication.