Skip to content
shellhacks.dev
Testing

Test a Shell Script That Calls curl or git with a Fake PATH

Test a script that calls curl or git by putting a fake executable first in PATH. The stub logs its arguments, and a call by absolute path bypasses it.

2 min read
Summarize in AI

A script calls an external tool, and the test must run without touching the network or the real program.

Shell
mkdir stubs
cat > stubs/curl <<'EOF'
#!/bin/bash
echo "curl $*" >> calls.log
echo '{"status":"ok"}'
EOF
chmod +x stubs/curl
cat > deploy.sh <<'EOF'
#!/bin/bash
curl -s https://example.invalid/health
EOF
cat > absolute.sh <<'EOF'
#!/bin/bash
/usr/bin/curl -s --max-time 1 https://example.invalid/health || echo "real curl was used"
EOF
PATH="$PWD/stubs:$PATH" bash deploy.sh
cat calls.log
PATH="$PWD/stubs:$PATH" bash absolute.sh
Text
{"status":"ok"}
curl -s https://example.invalid/health
real curl was used

The shell searches PATH from left to right, so an executable named curl in the first directory wins over /usr/bin/curl. The stub prints a canned response and appends its arguments to a log, which the test can read to assert how it was called. No code in the script under test needs to change. The lookup is defined in the shell command search rules.

A call with a slash in it skips the search, as the last run shows, so a script that hardcodes /usr/bin/curl is not stubbed. Bash remembers where it found a command, so call hash -r if the same shell has already run the real one. For stubs that must behave differently per call, have the script read a counter file. Bats projects often use the bats-mock helper for the same job.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.