Skip to content
shellhacks.dev
Testing

Simulate a Failing Command in a Bash Test with a Function

Simulate a failing command in a Bash test by defining a function with the command's name and exporting it with export -f. A script run by sh ignores it.

1 min read
Summarize in AI

You want to see how a script reacts when curl fails, without a broken network.

Shell
cat > fetch.sh <<'EOF'
#!/bin/bash
curl -fsS https://example.invalid/data -o data || { echo "download failed with status $?"; exit 1; }
echo "downloaded"
EOF
curl() { echo "curl: (22) simulated server error" >&2; return 22; }
export -f curl
bash fetch.sh
echo "bash script exit status: $?"
sh fetch.sh
echo "sh script exit status: $?"
unset -f curl
Text
curl: (22) simulated server error
download failed with status 22
bash script exit status: 1
curl: (6) Could not resolve host: example.invalid
download failed with status 6
sh script exit status: 1

A function takes precedence over the program of the same name, so curl() { return 22; } makes every call to curl fail with status 22, as curl -f does on an HTTP error. export -f passes the function to child Bash processes, and the script printed download failed with status 22. Running the same script with sh, which is dash here, ignored the function, called the real curl and got status 6 for the unresolvable host. See export.

Exported functions only reach Bash, and command curl bypasses the function. Remove it with unset -f curl when the test is done, or run each case in a subshell. A stub program early in PATH works for every shell and for scripts that call the full path only if you also change that path.

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.