SC2181 misleading for errexit
JohannesLorenz opened this issue · comments
For bugs
- Rule Id (if any, e.g. SC1000):
- My shellcheck version: 0.9.0 / online
- The rule's wiki page does not already cover this (https://shellcheck.net/wiki/SC2181)
- I tried on https://www.shellcheck.net/ and verified that this is still a problem on the latest commit
Here's a snippet or screenshot that shows the problem:
#!/bin/bash
funcname()
{
false
}
set -e
funcname
[ "$?" == 0 ] || echo "no"
Here's what shellcheck currently says:
[Line 10:](javascript:setPosition(10, 3))
[ "$?" == 0 ] || echo "no"
^-- [SC2181](https://www.shellcheck.net/wiki/SC2181) (style): Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.
Here's what I wanted or expected to see:
No warning or no misleading warning, and an exception on the SC2181 page.
Rationale: The warnings suggests ("Check exit code directly with e.g. 'if mycmd;'") to write code like this:
#!/bin/bash
funcname()
{
false
}
set -e
if funcname; then
echo yes
else
echo no
fi
This code passes, but is dangerous: errexit is now inactive in funcname
and all errors in funcname
or functions called by it will silently ignore errexit. So, after a function, doing something like rval=$?
and then testing $rval
seems the most clean to me (before funcname
calls return
, you need to set errexit off, and after catching rval
, you need to turn it on again).