Bash capture stderr of a function while using trap

88 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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:

$ cat tst.sh
#!/usr/bin/env bash

will_error() {
    echo "error" >&2
    return 100
}

foo() {
    trap 'output=$(will_error 2>&1); ret="$?"; trap - RETURN' RETURN
}

foo

printf 'output=%s\n' "$output"
printf 'ret=%s\n' "$ret"

$ ./tst.sh
output=error
ret=100

Don't use set -e but if you can't follow that advice then change the above code to this:

$ cat tst.sh
#!/usr/bin/env bash

set -e

will_error() {
    echo "error" >&2
    return 100
}

foo() {
    trap 'ret=0; output=$(will_error 2>&1) || ret="$?"; trap - RETURN' RETURN
}

foo

printf 'output=%s\n' "$output"
printf 'ret=%s\n' "$ret"

$ ./tst.sh
output=error
ret=100