shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

inconsistent handling of `test` and `[` when testing exit code

Open lacygoill opened this issue 2 years ago • 0 comments

For bugs

  • Rule Id: SC2181
  • My shellcheck version: 0.8.0
  • [x] The rule's wiki page does not already cover this
  • [x] 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
if test $? -gt 0; then
  :
fi

Here's what shellcheck currently says:

No error is given.

Here's what I wanted or expected to see:

This error is given:

In /path/to/script line 2:
if test $? -gt 0; then
        ^-- SC2181 (style): Check exit code directly with e.g. 'if ! mycmd;', not indirectly with $?.

Rationale: If we replace test with [, an error is given:

#!/bin/bash
if [ $? -gt 0 ]; then
  :
fi

And in bash, according to $ help [, [ is a synonym for test. If that's the case, I would expect SC2181 to be given for both test and [; not just for [.

lacygoill avatar Apr 17 '22 17:04 lacygoill