Everyday Guidebooks
Cover of Linux Shell Scripting

Cybersecurity & IT

Linux Shell Scripting: Test Your Scripts

A Practical Guide to Repeatable Checks, Failure Cases, and Safe Cleanup

by Todd Michael

Available now

A script that works once is not necessarily a script you can trust. Learn how to give your shell scripts controlled inputs, check what they produce, and repeat the same tests after every change.

Written for readers building linux command line shell scripting skills, this practical guide moves beyond watching for a successful run. You will capture output and exit status, make assertions, create temporary files, and test missing inputs and other failure cases. Step-by-step, text-based examples show how to isolate tests, clean up safely, and assemble a small reusable test harness.

The book also explores quoting, pipelines, file permissions, and other places where scripts can behave differently than expected. A final worked project brings the techniques together in a repeatable test suite you can adapt to your own scripts.

Basic familiarity with Linux commands and shell syntax is assumed; no graphical tools or paid testing services are required.

Contents
  1. 1. What Does It Mean to Test a Script?
  2. 2. Choosing Behaviors to Verify
  3. Start With a Small Contract
  4. Turn Promises Into Examples
  5. Build a Test Matrix
  6. Keep Output Streams and Status Separate
  7. A Small Starter Suite
  8. Read Failures Against the Contract
  9. Apply the Matrix to Your Own Script
  10. 3. Controlling Arguments and Input
  11. 4. Capturing Output and Exit Status
  12. 5. Writing Repeatable Assertions
  13. 6. Temporary Files and Isolated Workspaces
  14. Resolve the target before changing the working directory.
  15. 7. Cleanup That Survives Failure
  16. Create fixtures and run checks.
  17. 8. Testing File and Directory Operations
  18. 9. Probing Failure Paths
  19. Create a known-good source and a sentinel destination.
  20. Wrong argument count.
  21. Missing source.
  22. Existing destination.
  23. Copy failure: the destination's parent directory is absent.
  24. Success.
  25. 10. Quoting, Expansion, and Word Splitting
  26. Run this file from the practice directory.
  27. 11. Pipelines and Command Dependencies
  28. Run from the directory containing report.sh.
  29. Controlled filtering and a filename containing a space.
  30. The fixture has lines, but none contains this pattern.
  31. The first command fails while sort can still succeed.
  32. Invalid arguments must not create the named missing path.
  33. Use the normal PATH rather than the stub directory.
  34. 12. Building a Small Test Harness
  35. Resolve the script under test before entering any case workspace.
  36. Return nonzero only if capture itself could not be prepared.
  37. 13. Diagnosing Unreliable Tests
  38. 14. A Complete Script-Testing Project
  39. Other Books by Todd Michael

Read a sample: 1. What Does It Mean to Test a Script?

A script can run without visibly failing and still be wrong. It might print the expected message while returning a failure status, accept an argument it should reject, or write a file somewhere unexpected. It might work in the directory where its author wrote it but fail when launched from another location.

None of those possibilities makes a successful run worthless. Running a script is a useful way to learn what it does. But an observed result becomes a test only when you can compare it with an expectation.

A practical script test has a few identifiable parts:

- A starting condition: The files, environment, and other circumstances the script needs. - A controlled action: The command you run, including its arguments and input. - An expected result: What should appear on standard output or standard error, which exit status should be returned, and which side effects should occur. - A comparison: A check that distinguishes a match from a mismatch. - A way to repeat the check: Enough control over the starting condition and action to run the same test again.

Not every test needs to examine every kind of result. A script that prints a greeting may need no file-side-effect check. A script that updates a report almost certainly does. The important habit is to decide what matters before treating the run as evidence of correctness.

In this chapter, you will set up a small Bash practice workspace, write a script with a clear contract, and turn a manual observation into repeatable checks. The examples are intentionally small. Their purpose is to make the mechanics visible before the scripts and tests become more involved.

Use a Linux account and location where you are comfortable creating practice files. Do not run the examples as an administrator unless a particular exercise requires it; the exercises in this chapter do not. They do not need access to system configuration files or real user data.

Open a terminal and check that Bash is available:

bash bash --version

The command should print version information. The examples in this book use Bash, rather than relying on every behavior being supported by every shell. A terminal may start a different interactive shell, but you can still invoke the scripts explicitly with bash.

Create and enter a directory for this chapter:

bash mkdir -p "$HOME/shell-testing/chapter-01" cd "$HOME/shell-testing/chapter-01" || exit 1 pwd

The pwd command lets you confirm where you are. If you are entering these commands in a shell session you want to keep open, you may prefer to run the cd command on its own and check that it succeeded rather than use exit 1, which ends that shell if the directory change fails.

The examples below create or overwrite four files in this directory: greet.sh, test-greet.sh, greeting.out, and greeting.err. Before continuing, check that none contains anything you need to keep:

bash ls -la

If any of those names are already in use, choose a different practice directory or move the existing files somewhere safe. In particular, shell redirection with > truncates an existing file before the command runs, even if that command later fails.

For this first exercise, keeping the files visible is useful: you can inspect the script, its test, and the captured output. Later chapters will introduce isolated temporary workspaces and cleanup techniques so tests do not depend on leftover files.

The script for this chapter greets one person. Its contract is deliberately specific:

- Given exactly one nonempty argument, it prints Hello, followed by the argument and an exclamation mark, then a newline, to standard output. It returns status 0. - Given no arguments, an empty argument, or more than one argument, it prints a usage message to standard error and returns status 2.

The argument is treated as text. For example, a name containing a space is still one argument if it is passed as one. The contract does not claim to validate whether the text is a real name.

Create the script in the practice directory:

bash cat > greet.sh <<'EOF' #!/usr/bin/env bash

if (( $# != 1 )) || [[ -z $1 ]]; then printf 'Usage: %s NAME\n' "$0" >&2 exit 2 fi

printf 'Hello, %s!\n' "$1"

The quoted EOF marker tells the shell not to expand variables in the text as it writes the file. That matters here: the $1 in the file must remain part of the script, rather than being replaced by a value from the shell creating it.

The first line identifies Bash as the interpreter when the file is executed directly. For consistency, this chapter invokes the file with bash greet.sh, so it does not require executable permission.

The condition checks the argument count with $# and checks for an empty first argument with -z. The error message goes to standard error through >&2. On the successful path, printf uses a fixed format string and supplies the argument as data. Quoting "$1" preserves spaces and other characters as part of that one argument.

The usage message includes $0, the name used to invoke the script. If you invoke the script by a different path, that part of the message can differ. A test that checks the complete usage message should therefore control how it launches the script.

Try the ordinary case:

bash bash greet.sh Ada

You should see:

text Hello, Ada!

That is encouraging, but the visible line answers only one question: what…

More Cybersecurity & IT

Cover of The White Hat Bible, Volume 1The White Hat Bible, Volume 1Available nowCover of The White Hat Bible, Volume 2The White Hat Bible, Volume 2Available nowCover of The White Hat Bible, Volume 3The White Hat Bible, Volume 3Available nowCover of The White Hat Bible, Volume 4The White Hat Bible, Volume 4Available nowThe White Hat Bible, Volume 5Available nowCover of The White Hat Pocket GuideThe White Hat Pocket GuideAvailable now

About Todd Michael

Todd Michael is an American author and the founder of ToddMichael.tv. He writes practical, plain-English books on money, health, preparedness, technology, games, humor and more.

About the author Todd Michael · Todd Michael’s author site

Part of the ToddMichael.tv network.