5 Optional
Martin Bagge / brother edited this page 2024-09-02 08:21:25 +02:00

Optional checks

ShellCheck supports additional checks that are not enabled by default. These are generally subjective or stylistic.

Enabling an optional check

Checks can be enabled with flags or an enable directive in the file or .shellcheckrc:

#!/bin/sh
# shellcheck enable=require-variable-braces
echo "$RANDOM"  # Will emit a suggestion to use `${RANDOM}`

or put enable=require-variable-braces in a .shellcheckrc in your home directory or project root.

They can also be enabled on the command-line with -o:

$ shellcheck -o require-variable-braces myscript

Enabling all checks

It's a good idea to enable all warnings with -Wall in C, but this is not the case in ShellCheck. Optional checks are more subjective rather than more comprehensive, and may conflict with each other.

However, if you for debugging or evaluation purposes want to see what's available, you can enable them with -o all or enable=all as above.

Available checks

To see which checks are available in your version of ShellCheck, use the --list-optional flag.

Optional checks as of version 0.10.0:

$ shellcheck --list-optional
name:    add-default-case
desc:    Suggest adding a default case in `case` statements
example: case $? in 0) echo 'Success';; esac
fix:     case $? in 0) echo 'Success';; *) echo 'Fail' ;; esac

name:    avoid-nullary-conditions
desc:    Suggest explicitly using -n in `[ $var ]`
example: [ "$var" ]
fix:     [ -n "$var" ]

name:    check-extra-masked-returns
desc:    Check for additional cases where exit codes are masked
example: rm -r "$(get_chroot_dir)/home"
fix:     set -e; dir="$(get_chroot_dir)"; rm -r "$dir/home"

name:    check-set-e-suppressed
desc:    Notify when set -e is suppressed during function invocation
example: set -e; func() { cp *.txt ~/backup; rm *.txt; }; func && echo ok
fix:     set -e; func() { cp *.txt ~/backup; rm *.txt; }; func; echo ok

name:    check-unassigned-uppercase
desc:    Warn when uppercase variables are unassigned
example: echo $VAR
fix:     VAR=hello; echo $VAR

name:    deprecate-which
desc:    Suggest 'command -v' instead of 'which'
example: which javac
fix:     command -v javac

name:    quote-safe-variables
desc:    Suggest quoting variables without metacharacters
example: var=hello; echo $var
fix:     var=hello; echo "$var"

name:    require-double-brackets
desc:    Require [[ and warn about [ in Bash/Ksh
example: [ -e /etc/issue ]
fix:     [[ -e /etc/issue ]]

name:    require-variable-braces
desc:    Suggest putting braces around all variable references
example: var=hello; echo $var
fix:     var=hello; echo ${var}