linuxshellshellcheck

How to suppress irrelevant ShellCheck messages?


Environment

System: Linux Mint 19 (based on Ubuntu 18.04).

Editor: I use Visual Studio Code (official website) with ShellCheck plugin to check for errors, warnings, and hints on-the-fly.


ShellCheck

is a necessary tool for every shell script writer.

Although the developers must have put enormous effort to make it as good as it gets, it sometimes produces irrelevant warnings and / or information.

Example code, with such messages (warning SC2120 + directly adjacent information SC2119):


Example shell script snippet

am_i_root ()
# expected arguments: none
{
    # check if no argument has been passed
    [ "$#" -eq 0 ] || print_error_and_exit "am_i_root" "Some arguments have been passed to the function! No arguments expected. Passed: $*"

    # check if the user is root
    # this will return an exit code of the command itself directly
    [ "$(id -u)" -eq 0 ]
}

# check if the user had by any chance run the script with root privileges and if so, quit
am_i_root && print_error_and_exit "am_i_root" "This script should not be run as root! Quitting to shell."

Where:


Question

How do I disable these messages (locally only)?


Solution

  • Think it through before doing this!

    Do this only if you are 100.0% positive that the message(s) is really irrelevant. Then, read the Wiki here and here on this topic.


    Once you assured yourself the message(s) is irrelevant

    While generally speaking, there are more ways to achieve this goal, I said to disable those messages locally, so there is only one in reality.

    That being adding the following line before the actual message occurrence:

    # shellcheck disable=code
    

    Notably, adding text after that in the same line will result in an error as it too will be interpreted by shellcheck. If you want to add an explanation as to why you are suppressing the warning, you can add another hash # to prevent shellcheck from interpreting the rest of the line.

    Incorrect:

    # shellcheck disable=code irrelevant because reasons
    

    Correct:

    # shellcheck disable=code # code is irrelevant because reasons
    

    Note, that it is possible to add multiple codes separated by comma like this example:

    # shellcheck disable=SC2119,SC2120
    

    Note, that the # in front is an integral part of disabling directive!