shellcheck icon indicating copy to clipboard operation
shellcheck copied to clipboard

SC1009 parsing (apparently) valid if statement

Open fencepost-error opened this issue 6 years ago • 3 comments

For bugs

  • Rule Id (if any, e.g. SC1000): SC1009, SC1073, SC1072
  • My shellcheck version (shellcheck --version or 'online'): online
  • [x] I tried on 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/sh

if [ ! type hostname 2>/dev/null ] ; then
        ;
fi

Here's what shellcheck currently says:

Line 3	SC1009: The mentioned syntax error was in this if expression.
Line 3	SC1073: Couldn't parse this test expression. Fix to allow more checks.
Line 3	SC1072: Expected test to end here (don't wrap commands in []/[[]]). Fix any mentioned problems and try again.

Here's what I wanted or expected to see:

AFAICT this is valid (meaning it works under /bin/sh as expected), so I wasn't expecting to see any error message.

fencepost-error avatar Jan 05 '20 05:01 fencepost-error

AFAICT this is valid (meaning it works under /bin/sh as expected)

Neither of those assertions are true, and shellcheck is correct in throwing all three errors. Did you actually try running your script?

First of all, the semicolon in your then body is syntactically invalid (it should be a colon instead), but even ignoring that, your stderr redirection is hiding the main problem in your if test:

$ cat test.sh
#!/bin/sh
if [ ! type hostname ] ; then
        :
fi

$ sh test.sh
test.sh: 2: [: type: unexpected operator

What you wrote is exactly equivalent to:

if test ! type hostname ; then

which makes no sense per the test(1) man page. The correct syntax is in fact:

#!/bin/sh
if ! type hostname 2>/dev/null ; then
        :
fi

gromgit avatar Jan 06 '20 10:01 gromgit

Ah, sorry, that was pulled out of a 1000+ line script and it looks like I cut the test case down a bit too much, there was a bunch of other stuff there too. Let me relocate it and try and do a better minimised test case.

fencepost-error avatar Jan 07 '20 03:01 fencepost-error

OK, it was operator error, there was a problem in the aforementioned additional stuff that was present and when I tried to cut it down for a minimal test case I created the problem above. Apologies for the false positive.

fencepost-error avatar Jan 07 '20 05:01 fencepost-error