koalaman / shellcheck

ShellCheck, a static analysis tool for shell scripts

Home Page:https://www.shellcheck.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SC2181 misleading for errexit

JohannesLorenz opened this issue · comments

For bugs

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).