bashshellcheck

Bash script command and getting rid of shellcheck error SC2181


I have the following bash script:

dpkg-query --show --showformat='${Status}\n' "$i" 2> \
      /dev/null | grep "install ok installed" &> /dev/null
if [[ $? -eq 0 ]]; then
  l_var_is_desktop="true"
fi

and the ShellCheck utility (https://www.shellcheck.net/) is giving me the following output:

$ shellcheck myscript

Line 17:
    if [[ $? -eq 0 ]]; then
          ^-- SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

$ 

The link to this warning is the following: https://github.com/koalaman/shellcheck/wiki/SC2181

What is the best way for modifying this. The command is really too long to put into one line. I would like to avoid using ShellCheck ignore rules.

I've tried creating a local variable and storing the output of the command, but this breaks other rules.


Solution

  • The command doesn't really get much longer by putting it directly in if, you're just adding 3 characters.

    if dpkg-query --show --showformat='${Status}\n' "$i" 2> \
        /dev/null | grep "install ok installed" &> /dev/null
    then
        l_var_is_desktop="true"
    fi