I have a function that will error in specific cases. I want to test the code I've written to see if it's erroring for those cases. For simplicity let's say the function is from a file with the following:
set -e
will_error() {
echo "error" >&2
exit 100
}
In my test file I want to be able to capture the output of the function will_error
and compare it to what's expected to be printed to stderr if it was run for real.
test_no_default_no_argument() {
trap ':' EXIT
result=$(will_error 2>&1)
if [ "$result" != "error" ];then
echo "test failed"
exit 1
fi
}
test_no_default_no_argument
How do I capture the output of will_error
and the return code to use for validation?
I don't know why your example changed so much from when it was about using
trap 'will_error 2>&1' RETURN
but, in case you still have your original question, this is what I think you were originally trying to do:Don't use
set -e
but if you can't follow that advice then change the above code to this: