if ! <command> (...) vs. <command> ; if [ $? -eq 0 ] (...)
6
votes
1
answer
7335
views
I am working on a shell script and decided to check my work via shellcheck.net . I am able to get functionally the same behavior of the following two lines in my script:
findmnt /dev/sda1 >/dev/null ; if [ $? -eq 0 ]; then echo 1; else echo 0; fi
vs.
if ! findmnt /dev/sda1 >/dev/null; then echo 0; else echo 1; fi
However shellcheck throws :
> SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly
> with $?.
It is not immediately clear to me which to use. I do see: https://github.com/koalaman/shellcheck/issues/1167 which seems to have amended this for several possible values. I want to be sure that I am writing something that uses best practices and will run without issue and report accurately.
Asked by Kahn
(1827 rep)
Sep 28, 2021, 06:45 PM
Last activity: Sep 28, 2021, 07:47 PM
Last activity: Sep 28, 2021, 07:47 PM