0PricingLogin
Linux Command Line & Bash Scripting Mastery · Lesson

Mocking Commands and Stubbing External Tools

Override PATH and define fake binaries to test scripts without touching real systems.

Why Mock Commands in Bash Tests?

When you test a Bash script that calls curl, aws, git, or any external tool, you face a problem: real calls hit the network, modify state, cost money, or simply fail in a CI environment where those tools aren't installed.

Mocking means replacing the real command with a fake one that you control. Your fake (the stub) returns predictable output and exit codes, so your test is fast, isolated, and reproducible.

  • No network or cloud access needed
  • Tests run in milliseconds instead of seconds
  • You can simulate errors that are hard to trigger on real systems
  • CI pipelines stay clean and dependency-free

Bash gives you a surprisingly simple mechanism to do this: just put your fake binary somewhere earlier on $PATH than the real one.

How PATH Lookup Works

When the shell executes a command like curl, it searches each directory in $PATH from left to right and runs the first match it finds.

This means if you prepend a directory that contains your own curl script, the shell will never reach /usr/bin/curl.

The override pattern:

  1. Create a temporary directory (your stub bin)
  2. Write a fake executable with the same name as the real command
  3. Prepend that directory to PATH
  4. Run your script under test — it calls your stub, not the real binary
  5. Clean up the temp directory after the test

This works without root access, without modifying system files, and without any special framework.

All lessons in this course

  1. Unit Testing Functions with Bats-core
  2. Mocking Commands and Stubbing External Tools
  3. Fixtures, Temp Environments, and Coverage
  4. Running Shell Tests in CI Pipelines
← Back to Linux Command Line & Bash Scripting Mastery