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:
- Create a temporary directory (your stub bin)
- Write a fake executable with the same name as the real command
- Prepend that directory to
PATH - Run your script under test — it calls your stub, not the real binary
- 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
- Unit Testing Functions with Bats-core
- Mocking Commands and Stubbing External Tools
- Fixtures, Temp Environments, and Coverage
- Running Shell Tests in CI Pipelines