Native rules
Besides ShellCheck's checks, which keep their SC codes, shell-lsp has rules of its own. Their codes start with SL, and they are configured the same way: # shellcheck disable=SL1001 silences one, lint.exclude drops one for a workspace, and optional rules are switched on with enable= or lint.optional. checks.md lists every check, SC and SL, with its severity and a one-line summary.
The injection rules follow values that come from outside the script—its command-line arguments, getopts option values (OPTARG) and input taken with read, mapfile or readarray—through assignments, loops and function arguments. They only fire when such a value is pasted into a larger piece of code or a path. Running a whole argument (eval "$1", bash -c "$1", . "$1") is treated as deliberate. A value counts as checked once it has been tested with [[ … =~ … ]], a [[ … == pattern ]] match or a case statement earlier in the same function. Command output ($(…)) is not treated as outside data, and neither is what printf -v writes with a fixed format whose conversions are all numeric, such as printf -v code '%d' "'$char", since that is only ever a number.
SL1001
eval runs untrusted data as code. A value from outside the script is pasted into the code eval runs, so a value like x; rm -rf ~ runs commands.
name=$1
eval "echo hello $name" # SL1001Pass the value as data instead, for example printf 'hello %s\n' "$name", or check it against a fixed set of values before it reaches eval.
SL1002
A shell -c script is built from untrusted data. A value from outside the script is pasted into the script that sh -c, bash -c, su -c (or one of them behind sudo, doas, env, nohup, nice, timeout or setsid) runs.
sudo sh -c "echo $1 > /etc/motd" # SL1002
sudo sh -c 'echo "$1" > /etc/motd' _ "$1" # safe: $1 stays an argumentSL1003
Untrusted data is evaluated as arithmetic. The rule is optional (arithmetic-injection). Bash and mksh evaluate array subscripts inside arithmetic, so a value like a[$(reboot)] runs a command in (( n > 3 )), $(( n + 1 )) and [[ $n -eq 3 ]]. zsh evaluates the subscript without running the command, ksh93u+m rejects the command substitution as an arithmetic syntax error, and POSIX sh, dash and busybox sh have no arrays, so the rule only applies to bash and mksh scripts. [ "$n" -eq 3 ] is safe because test only accepts plain integers.
#!/bin/bash
# shellcheck enable=arithmetic-injection
n=$1
(( n > 3 )) # SL1003
[[ $n =~ ^[0-9]+$ ]] || exit 1 # validated from here onSL1004
A sourced path is built from untrusted data. A value from outside the script is pasted into the path that source or . loads, so ../ or an absolute path can make it run any file.
. "/etc/app/$1.conf" # SL1004: $1=../../tmp/evilSL1005
Downloaded code runs unchecked. A script fetched with curl or wget is piped straight into a shell, run with sh -c "$(curl …)", bash <(curl …), source <(curl …) or . /dev/stdin, or passed to eval, so whatever the server or anyone on the way sends is executed, and a connection cut halfway can run half a script. Downloads written to a file (curl -o file, curl -O, wget without -O -) are not reported, because the file can be checked before it runs.
curl -fsSL https://example.com/install.sh | sh # SL1005
curl -fsSLo install.sh https://example.com/install.sh
echo "$expected_sha256 install.sh" | sha256sum -c - && sh install.shSL1006
A sensitive path is made writable by every user. chmod, mkdir -m or install -m gives others write permission (777, 666, 0777, 2777, o+w, a+w, a=rwx and the like) on a path that other users must not be able to change: the root directory, a system directory such as /etc, /usr, /bin, /sbin, /boot, /root or anything under them, /var or /home themselves, a home directory (~, $HOME, /home/name), a shell startup file in it such as ~/.bashrc, ~/.ssh or ~/.gnupg and their contents, authorized_keys, or an SSH private key such as id_ed25519. Anyone on the machine can then replace a program, add a key that lets them log in, or put commands in a file that runs as the owner. The command is also found behind sudo, env and the other wrappers. Symbolic modes without o or a, such as +w, depend on the umask and are not reported; nor are modes that cannot be read, such as "$mode", or a umask, which is not tied to any path.
sudo chmod -R 777 /etc/nginx # SL1006
chmod 666 ~/.ssh/authorized_keys # SL1006
chmod 600 ~/.ssh/authorized_keysSL2001
A function in a script is never called. Nothing in the script, in the files it sources, or in functions those call ever runs the function, so it is dead code. Only executed scripts are checked: files with a #! line whose top level does real work. Libraries that only define functions and settings, and scripts that detect being sourced (through BASH_SOURCE, ZSH_EVAL_CONTEXT, zsh's ${(%):-%x}, $0 or a top-level return), are left alone because their functions are meant for other files. So are startup files such as .zshrc or .bashrc and files that set up an interactive shell (with compinit, promptinit, compdef, add-zsh-hook, bindkey, bind or complete), whose functions are commands for the user to type. The name counts as used wherever it appears as a word, including inside strings such as trap 'cleanup' EXIT. A command name built at run time, like "cmd_$1", counts as a use of every function that starts with cmd_; running "$@" as a command, eval, or listing functions with compgen -A function or declare -F turns the check off for the file. Hook functions the shell calls itself, such as command_not_found_handle, precmd or TRAPINT, are never reported.
#!/bin/bash
helper() { echo help; } # SL2001
main() { echo "$1"; }
main "$@"SL2002
An @ transformation the shell does not know. ${name@op} applies one of a fixed set of transformations: U, u, L, Q, E, P, A, K, a and k in bash, Q and # in mksh. Bash only checks the operator when it expands the parameter, so the script parses and an unset variable expands to nothing, but as soon as the variable has a value the expansion fails with "bad substitution" and the command does not run. The usual cause is a typo, or a template placeholder such as ${PREFIX_@suffix@} left in a script meant to be filled in first.
#!/bin/bash
name=world
echo "${name@q}" # SL2002: the operator is QSL2003
A declaration assigns a name that is not a variable name. export, declare, local, readonly and typeset take name=value arguments, but the shell parses an argument like my-var=1 or 1st=a as an ordinary word and the command fails at run time with "not a valid identifier", so nothing is assigned and, under set -e, the script stops. Arguments whose name comes from an expansion (export "$name=value") or contains a backslash are left alone, since the shell expands them before checking.
#!/bin/bash
export my-var=1 # SL2003: write my_varSL2004
A trap is set inside a subshell. A command substitution and every pipeline stage that runs in a subshell (all but the last in bash without lastpipe) get their own copy of the traps, so a trap set there only fires for that subshell and is gone once it ends. Saving traps with $(trap -p), resetting one with trap - SIG, and traps inside an explicit ( … ) subshell, which are usually meant for that subshell, are not reported.
#!/bin/bash
seq 3 | while read -r n; do trap 'echo bye' EXIT; done # SL2004SL2005
exit only leaves a subshell and nobody checks its status. exit inside a command substitution or a pipeline stage ends that subshell, not the script. The status it leaves behind still reaches the script when the substitution is the value of a plain assignment or the stage is the last of the pipeline (or pipefail is on), so the rule stays quiet when that status is checked: by set -e, !, &&, ||, an if or while condition, a following $? or PIPESTATUS, or because the statement is the last one in its block.
#!/bin/bash
dir=$(cd "$1" || exit 1; pwd) # SL2005: the script goes on with an empty $dir
dir=$(cd "$1" && pwd) || exit 1 # checkedSL2006
A temporary file or directory is never removed. mktemp creates the file or directory, but nothing passes the variable that holds it to rm, rmdir, mv or a cleanup function, and no trap names it, so every run leaves it behind. Only executed scripts are checked, as for SL2001. The variable counts as handled once it is copied into another variable or array, reassigned, printed or exported, and mktemp -u, -p DIR and templates outside the temporary directory are left alone. The fix adds an EXIT trap that removes it, when the script has no EXIT trap yet.
#!/bin/bash
work=$(mktemp -d) # SL2006
cp -R src "$work"The fix inserts trap 'rm -rf -- "$work"' EXIT after the assignment.
SL2007
A function runs pushd but never popd. Every call leaves its caller in another directory with one more entry on the directory stack. pushd inside a subshell, pushd without a directory, pushd -n, stack rotations, and scripts that pop the stack outside the function (a leave function or a popd at the call site) are not reported.
#!/bin/bash
build() {
pushd "$1" >/dev/null || return # SL2007
make
}SL2008
A ${…} the shell rejects when it runs it. Bash, sh and mksh accept some malformed expansions when they read the script, such as ${} or a template placeholder like ${@name@}, and only fail with "bad substitution" when the line runs, so the script stops there. Forms with a more specific explanation are reported under their own codes instead: SC2082 for ${$x}, SC2296 for a name that starts with a character no parameter can start with.
#!/bin/bash
echo "${}" # SL2008SL2009
A disabled check that nothing here reports. A # shellcheck disable= directive lists a code, or a range of codes, that no finding in the lines it covers has, so it silences nothing; often the problem was fixed and the directive stayed behind. Codes the linter does not have at all are reported too. disable=all, optional checks that are not turned on, and the checks whose findings depend on whether sourced files can be found (SC1090, SC1091, SC1094 and SC2154) are left alone. The quick fix removes the code, or the whole directive when nothing in it is used.
#!/bin/bash
# shellcheck enable=unused-directives
# shellcheck disable=SC2086 # SL2009: the argument below is already quoted
echo "$1"SL2010
A NUL byte cuts a $'...' string short. Shell variables and command arguments are C strings, so an escape that produces a NUL byte (\0, \x00, \u0000, \c@) ends the string there and everything after it is silently dropped: $'a\x00b' is just a. zsh can hold NUL bytes and is not checked.
#!/bin/bash
marker=$'\xd8\x00' # SL2010: marker holds only \xd8
printf 'a\0b' > record # a NUL byte written to a file survivesSL2011
Two bounds on the same value leave no number in between. In (( )), $(( )) and the other arithmetic contexts, an && chain that requires a variable to be at least one constant and at most a smaller one can never be true, which usually means a typo in one of the bounds. Constants are read the way the shell reads them, in decimal, octal (010), hexadecimal (0x1f) or an explicit base (2#1010).
#!/bin/bash
(( cp >= 0xd800 && cp <= 0xdff )) && return 1 # SL2011: 0xdff < 0xd800; meant 0xdfffSL2012
&& and || are mixed in [[ ]] without parentheses. The rule is optional (require-test-grouping). Inside [[ ]], && binds tighter than ||, so [[ $a && $b || $c ]] means [[ ( $a && $b ) || $c ]] and [[ $a || $b && $c ]] means [[ $a || ( $b && $c ) ]]. That is well defined, but readers often take the operators to apply left to right, and among shell commands a && b || c does exactly that. The quick fix adds the parentheses the shell already implies, so it never changes what the test does. It is optional because such tests are usually written on purpose, like the common version check [[ $major -eq 4 && $minor -ge 4 || $major -gt 4 ]].
#!/bin/bash
# shellcheck enable=require-test-grouping
[[ -f $conf && -r $conf || -n $default ]] # SL2012
[[ ( -f $conf && -r $conf ) || -n $default ]]SL2013
A sourced file is found relative to where the script is run from. The rule is optional (check-relative-sources). . ./lib.sh and source lib/common.sh resolve the path against the working directory of whoever runs the script, so run from another directory the script loads a different file or none. A name without a slash, such as . lib.sh, is looked up in PATH; bash, and zsh's source, then also try the working directory, while sh, dash, busybox, ksh and zsh's . never look next to the script. The path is worked out the way following sourced files works it out, so a path built from the script's own location, such as "$(dirname "$0")/lib.sh", "${BASH_SOURCE%/*}/lib.sh" or "$here/lib.sh" with here=$(cd "$(dirname "$0")" && pwd), is fine, and so is a path only known at run time, one with a default the caller can override ("${srcdir:-.}/lib.sh") and a build-time placeholder such as @out@. Nothing is reported after the script changes directory with cd or pushd, for a sourced file named with a # shellcheck source= directive, in shell startup files such as .bashrc, which the shell reads from a fixed place, or in Bats files, whose tests run from the directory the test runner is started in. The quick fix anchors the path with dirname.
The rule is optional because many test suites, such as the Linux kernel selftests, are always run from their own directory and source their helpers by bare name.
#!/bin/bash
# shellcheck enable=check-relative-sources
. ./lib.sh # SL2013
. "$(dirname "${BASH_SOURCE[0]}")/lib.sh"SL2014
A function assigns a variable it did not declare local. The rule is optional (require-local-variables). Variables in a shell function are global unless declared with local (typeset in a ksh93 function name), so an assignment, a for loop, read, getopts or (( n = 0 )) inside the function changes a variable of the same name in its caller, and the value outlives the call. The Google Shell Style Guide asks for local on every function-specific variable. A variable is left alone when it is declared local earlier in the function or in one that encloses it; when the script declares it global anywhere with export, readonly, declare -g or a declare at the top level; when the top level assigns it too, which makes it a global by design and is SL2015's concern; when code outside the function reads it without assigning it, which shows it is the function's output; and for the shell's own variables, such as REPLY, OPTIND, IFS or COMPREPLY. Each variable is reported once per function. POSIX sh has no local, so sh scripts are not checked. ksh93 has no local either, and its functions written as name() are not checked because typeset does not make a variable local there; mksh has local in both function forms.
#!/bin/bash
# shellcheck enable=require-local-variables
count_lines() {
total=0 # SL2014
local line
while read -r line; do total=$((total + 1)); done < "$1"
echo "$total"
}SL2015
A global variable is given a new value. The rule is optional (avoid-global-reassignment). The Google Shell Style Guide prefers globals that are set once, ideally made readonly, so that a reader can trust a global's value anywhere in the script. Two kinds of change are reported:
- At the top level, a plain assignment to a variable that an earlier top-level assignment already set, unless the two sit in different branches of the same
iforcase, where only one of them runs. Updates that build on the old value are accumulation rather than a new value and are left alone:+=,n=$((n + 1)),list="$list $item",(( n++ ))and assignments to one array element. So areforloop variables and the variablesread,getoptsandmapfilefill, which the shell sets rather than the script. - In a function, any write to a variable the top level also sets, including updates and loops, unless the function declared it local first: the function changes state the rest of the script depends on.
Assignments before the variable is made readonly at the top level are the style guide's own pattern for settings, such as defaults that option parsing overrides, and are not reported; neither are function writes to a variable the top level makes readonly. Each variable is reported once per function, and the shell's own variables, such as PATH or IFS, are never reported. SL2014 covers function variables the top level does not set.
#!/bin/bash
# shellcheck enable=avoid-global-reassignment
mode=fast
mode=slow # SL2015
reset() { mode=fast; } # SL2015SL2016
A pattern uses a glob operator whose shell option is never turned on. zsh's extended glob operators (^, ~, #, ##, the globbing flags such as (#i) and (#b), and repetitions such as (#c2,3)) only work with setopt extendedglob; without it zsh matches them as plain text, so [[ $answer == (#i)yes ]] tests for the text (#i)yes. bash's ?(…), *(…), +(…), @(…) and !(…) need shopt -s extglob: in the arguments of a command or a case pattern bash rejects them as a syntax error, and in a ${var//pattern/…} expansion it matches them as plain text. bash reads a whole line, and a whole function definition, before it runs any of it, so shopt -s extglob has to come on an earlier line, outside the function that uses the glob; inside [[ … == … ]] the operators always work. bash's ** only descends into subdirectories with shopt -s globstar. ksh always has extended globs. An option counts as on when the file turns it on anywhere, with setopt, set -o, shopt -s or emulate -o, and zsh completion functions (#compdef, #autoload) run with extendedglob on. A file that sets options from a variable (setopt $opts) is not checked, and in a file without a shebang, which runs inside whatever sources or autoloads it, the finding is only informational, since that code may have turned the option on. The fix adds the command on a line of its own: setopt local_options extendedglob as the first command of a zsh function, otherwise above the line that uses the operator.
#!/bin/bash
rm -- !(keep).log # SL2016#!/bin/zsh
[[ $answer == (#i)yes ]] && print agreed # SL2016SL2017
A capture variable is read, but nothing in the file sets it. zsh fills $match, $mbegin and $mend from the parenthesised groups of a pattern that has the (#b) flag, and $MATCH, $MBEGIN and $MEND from one with (#m); [[ … =~ … ]] sets them too. bash fills BASH_REMATCH only from [[ … =~ … ]]. When the file reads one of them but has no such pattern or test, and does not assign the variable itself, the read sees whatever an earlier match left behind, usually nothing. A forgotten (#b) is the common cause.
#!/bin/zsh
setopt extendedglob
print ${line//(*)=(*)/$match[2]} # SL2017SL2018
An unquoted & in a bash replacement inserts the matched text. Since bash 5.2 the patsub_replacement option, on by default, makes an & in the replacement of ${var/pattern/replacement} stand for the text the pattern matched, as in sed; earlier versions insert a literal &. A script written for one reads differently on the other, so a literal & is better written \&, which every version reads the same way. The rule is silent when the file turns the option off with shopt -u patsub_replacement. The fix escapes the &.
#!/bin/bash
echo "${title//and/&}" # SL2018
echo "${title//and/\&}" # safeSL2019
zsh rejects a pattern as bad. A group that is never closed, an unknown globbing flag such as (#x) or a repetition count such as (#c3,1) makes zsh stop with "bad pattern" when the pattern is used, which aborts the command.
#!/bin/zsh
setopt extendedglob
print ${name//(#x)a/b} # SL2019SL2020
An external command does what a parameter expansion or [[ ]] does without a new process. Each of these starts at least one process to work on a single value, which the shell can do itself:
| Command | In the shell | Differs |
|---|---|---|
$(basename "$f") | ${f##*/}; ${f:t} in zsh | for a path that ends in /; in zsh only for / itself |
$(dirname "$f") | ${f:h}, in zsh only | for a path that starts with // |
$(pwd) | $PWD | when the environment hands the shell a PWD spelled differently from the directory, as Git Bash on Windows can |
$(echo "$x" | tr a-z A-Z) | ${x^^}; ${(U)x} in zsh | letters outside a-z are converted too |
$(echo "$x" | tr A-Z a-z) | ${x,,}; ${(L)x} in zsh | letters outside A-Z are converted too |
$(echo "$x" | tr -d c) | ${x//c} | |
$(echo "$x" | tr a b) | ${x//a/b} | |
$(echo "$x" | cut -d: -f1) | ${x%%:*} | for a value of several lines |
$(echo "$x" | cut -d: -f2-) | ${x#*:} | for a value of several lines |
echo "$x" | grep -q text | [[ $x == *"text"* ]] |
The value may also come from printf '%s\n' "$x" or a here-string (<<< "$x"), and the commands may be given as /usr/bin/basename and the like. tr is rewritten for the case conversions above and for single characters; grep only for a fixed string, without -i, -v or other options. The case conversions need bash 4 or later, which macOS does not ship as /bin/bash, or zsh; the rest bash, ksh or zsh, except for basename, pwd and cut, whose rewrites are POSIX. dirname is only rewritten in zsh: the POSIX ${f%/*} keeps a path without a /, such as a $0 of script.sh, where dirname gives .. SC2001 does the same for sed 's/old/new/' and fixes literal substitutions, and SL2021 covers $(cat file). Beyond the differences listed, a rewrite keeps trailing newlines of the value that the command substitution would strip, and echo mangles a value such as -n or one with backslashes that the expansion keeps as it is, so the fixes are offered for review.
#!/bin/bash
name=$(basename "$path") # SL2020
upper=$(echo "$name" | tr a-z A-Z) # SL2020
if echo "$upper" | grep -q READ; then echo found; fi # SL2020SL2021
$(cat file) runs cat to read a file the shell can read itself. The rule is optional (useless-use-of-cat, which also turns on SC2002). In bash, ksh and zsh $(<file) reads the file without starting cat; only the error message for a missing file differs. POSIX sh has no $(<file), so sh scripts are not checked.
#!/bin/bash
# shellcheck enable=useless-use-of-cat
config=$(cat "$file") # SL2021SL2022
A regular expression escape does not work where =~ uses it. POSIX regular expressions, which [[ … =~ … ]] uses in bash and zsh, have no \d or \D: the C library reads them as the letter d, so [[ $n =~ ^\d+$ ]] accepts ddd and rejects 42. In bash the quoted text of the word is matched literally, so '\d' there matches a backslash followed by d. bash also treats a backslash written directly in the word as quoting the next character, so \w, \s, \b, \< and their uppercase forms match the plain letters instead of the GNU escapes; the escapes only reach the regular expression when it is kept in a variable (re='^\w+$'; [[ $x =~ $re ]]). The fix writes [0-9] for \d and [^0-9] for \D where that keeps its meaning.
#!/bin/bash
[[ $1 =~ ^\d+$ ]] && echo number # SL2022
[[ $1 =~ ^[0-9]+$ ]] && echo number # safeSL2023
A [key]=value element in an associative array's key value list. In bash 5.1 and later and in zsh, an associative array assignment whose first element has no [key]= is read as alternating keys and values. A later element written [key]=value is then not a subscript assignment: bash stores its text, brackets and = included, as the next key or value, and zsh stops with "bad [key]=value syntax for associative array". Write every element of the list the same way, either all as key value pairs or all as [key]=value.
#!/bin/bash
declare -A port
port=(http 80 [https]=443) # SL2023: the key is the text [https]=443
port=([http]=80 [https]=443) # safeSL2024
An associative array's key value list has an odd number of elements. When an associative array assignment is read as alternating keys and values, the last key of an odd-length list has no value. zsh rejects the assignment with "bad set of key/value pairs for associative array"; bash 5.1 and later quietly give that key an empty value, which is almost always a forgotten value rather than an intended one. The elements are only counted when none of them can expand to a different number of words, such as an unquoted $rest, "${list[@]}", a command substitution, a glob or a brace expansion. Write an intended empty value as ''.
#!/bin/bash
declare -A port
port=(http 80 https) # SL2024
port=(http 80 https 443) # safeThe embedded-language rules check awk, sed and jq programs written inside the script with built-in parsers; no awk, sed or jq binary is run. A program is checked when it is a literal argument (awk '...', sed -e '...', jq -r '...') or a quoted here-document fed to awk -f - or sed -f -, also when the command runs behind sudo, env, nice, timeout, xargs, find -exec and the other wrappers. Programs that contain shell expansions, come from files, or contain the {} or xargs -I placeholder substituted at run time are skipped rather than guessed at.
Each error is reported at its exact position inside the shell string. After an error the parser resumes at the next line of a sed script, the next statement of an awk program or the next top-level | stage of a jq filter, so up to ten errors are reported per program; where it cannot tell how the program continues, such as after a string that is never closed, it stops rather than report follow-on errors.
SL3001
An awk program does not parse. The program given to awk, gawk, mawk, nawk or original-awk has a syntax error, so awk refuses to run it. Common gawk extensions (BEGINFILE, switch, @include, **, |&) are accepted.
Regular expression constants (/re/) and string literals on the right of ~ or !~ are read as extended regular expressions after awk's own string escapes, and only mistakes every awk rejects are reported: a group or bracket expression that is never closed, an unknown character class, an empty range such as [z-a] and a trailing lone \. Constructs that awks read differently, such as a leading *, an unmatched ) or braces, are left alone.
awk '{ print $1 ' file.txt # SL3001: `{` is never closed
awk '$2 ~ /^(GET|POST/' log # SL3001: `(` is never closedSL3002
A sed script does not parse. The script given to sed or gsed has a syntax error, so sed refuses to run it. GNU extensions such as 0,/re/, first~step, addr,+N, T, e, F and z are accepted. The pieces given with several -e or --expression options are read together as one script, so a branch with b, t or T must name a label that a : somewhere in them defines. Labels end at a blank, ;, # or }, as in GNU sed.
The regular expressions of addresses and s commands are read as POSIX basic expressions, or extended ones under -E, -r or --regexp-extended, and only mistakes GNU sed rejects are reported: a group, bracket expression or interval that is never closed, a closing parenthesis without its opening one, an unknown character class, an empty range such as [z-a] or a range that starts or ends at a character class, an interval that is not a count such as {2}, {1,3}, {2,} or {,3}, whose minimum is above its maximum or whose count exceeds 32767, a quantifier with nothing to repeat in an extended expression (at the start, after (, | or an anchor), and a back-reference such as \2 to a group the expression does not have, to a group that is not closed yet, or to a group in another alternative, in the expression or in the replacement of s.
sed 's/a/b/x' file.txt # SL3002: unknown option to `s`
sed 's/\(.*\)=\(.*\)/\2=\3/' conf # SL3002: there is no group 3SL3003
A jq filter does not parse. The filter given to jq, gojq or jaq has a syntax error, so jq refuses to run it.
The pattern of test, match, capture, scan, split/2, splits, sub and gsub is checked when it is a single string literal and the flags, if given, are a literal without x. jq compiles patterns with Oniguruma only when the filter runs, so these are run-time errors; only clear ones are reported: a group or bracket expression that is never closed, a ) without its (, a quantifier with nothing to repeat, an empty range such as [z-a], an interval whose minimum is above its maximum and a trailing lone \.
jq '.items[] | | .name' data.json # SL3003: unexpected `|`
jq '.[] | select(.id | test("^(a|b"))' data.json # SL3003: `(` is never closedThe style guide rules, SL4xxx, check the rules of the Google Shell Style Guide that a linter can verify. Each one is optional and named with the google- prefix, so # shellcheck enable=google-shebang or lint.optional turns on a single rule. They follow one organisation's conventions rather than point at mistakes, so the strict profile leaves them out; enable=all includes them. Bats files, whose shape their test runner decides, are not checked.
SL4001
An executable does not start with #!/bin/bash. The rule is optional (google-shebang). The guide makes bash the only shell for executables and asks for the exact interpreter line #!/bin/bash, with as few flags as possible, so #!/bin/sh, #!/bin/zsh, #!/usr/bin/bash and #!/usr/bin/env bash are all reported. Files without a #! line are libraries and are not checked. For a bash interpreter line without flags, the quick fix writes #!/bin/bash. Here the first line is reported:
#!/usr/bin/env bash
# shellcheck enable=google-shebang
echo "hello"SL4002
A file does not open with a comment about its contents. The rule is optional (google-file-header). The guide asks every file, script or library, to start with a top-level comment giving a brief overview of what it holds. After the #! line (or a zsh #compdef tag), blank lines, bare # lines and # shellcheck directives are skipped; the next line must be a comment, or the first line of code is reported. Whether the comment really describes the file is up to the reader.
#!/bin/bash
# shellcheck enable=google-file-header
echo "hello" # SL4002SL4003
A TODO comment does not name an owner. The rule is optional (google-todo). The guide writes TODO in capitals followed by the name, e-mail address or other identifier of the person with the best context, in parentheses: # TODO(mrmonkey): Handle the edge cases. A comment counts as a TODO when it contains the word TODO in capitals or starts with todo in any case, so # todo: retry and # Fix this. TODO: retry are reported while ordinary prose such as "things to do", or a quoted 'TODO', is not.
#!/bin/bash
# shellcheck enable=google-todo
# TODO: retry on timeouts # SL4003
# TODO(alice): retry on timeouts
curl -fsS https://example.comSL4004
A function that is not short has no header comment. The rule is optional (google-function-comments). The guide asks for a comment directly above every function that is not both obvious and short, and above every function in a library whatever its size. Whether a function is obvious is a judgement a linter cannot make, and the guide gives no number for short, so the rule takes a function of at most 10 lines, counted from its name to its closing brace, as short and obvious, and reports longer ones. In a file without a #! line, which the guide treats as a library, every function needs a comment. # shellcheck directives above a function do not count as its comment.
# Helpers for the backup scripts.
# shellcheck shell=bash enable=google-function-comments
backup() { # SL4004
tar -czf "$1.tgz" "$1"
}SL4005
A function header comment leaves out a section the function needs. The rule is optional (google-comment-sections). The guide's function comments describe the function and then list, under Globals:, Arguments:, Outputs: and Returns:, the global variables it uses or changes, the arguments it takes, what it writes to standard output or error and the values it returns besides the status of its last command. Its examples only list the sections that apply, so for a function that already has a header comment the rule asks for each section the function's own body calls for:
Globals:when it reads or writes a variable the script assigns outside anylocal, other than the shell's own variables;Arguments:when it reads$1,$@,$#or another positional parameter, or runsshiftorgetopts;Outputs:when it runsecho,printforprintwithout sending standard output to a file or into a command substitution;Returns:when it runsreturnwith a value.
Nested functions count for themselves only. Functions without a header comment are SL4004's concern.
#!/bin/bash
# shellcheck enable=google-comment-sections
# Print a greeting.
greet() { # SL4005: no Arguments: or Outputs:
echo "hello $1"
}
greet worldSL4006
A script is longer than 100 lines. The rule is optional (google-script-length). The guide reserves shell for small utilities and wrappers and asks for a script of more than 100 lines to be rewritten in a more structured language, before it grows further. Every line counts, comments and blank lines included, since the guide gives no other measure. The finding sits on the first line of the file.
SL4007
A script with functions does not end with main "$@". The rule is optional (google-main). The guide requires a function called main in any script long enough to define at least one other function, and makes main "$@" the last line that is not a comment, so the start of the program is easy to find and its variables can be local. The rule applies to scripts that run on their own, as SL2001 decides it: files with a #! line that are not libraries, startup files or files meant to be sourced, which is why a script that runs main "$@" only when it is not sourced is left alone. It reports the last statement when the script has no main, and when it has one but ends with something other than exactly main "$@".
#!/bin/bash
# shellcheck enable=google-main
greet() { echo "hello $1"; }
greet "$@" # SL4007Justfiles and Makefiles
shell-lsp also reads the just and make syntax around the shell in justfiles and Makefiles. These checks have SL5 codes for justfiles and SL6 codes for Makefiles. Every justfile check was compared with what just 1.58 itself rejects, and every Makefile check with GNU Make 4.4. Missing names are only reported when every import, mod and include that could define them was found, so a justfile or Makefile that pulls in a file generated at build time gets no false alarms. The same holds for unused names, and for a file whose includer is unknown: a .just, .mk or .mak file that nothing in the workspace imports or includes, or a Makefile with an $(eval ...) whose text is computed, may define and use names that the analysis cannot see. lint.exclude turns them off like any other check; directives inside the file do not apply, since the file is not a shell script.
SL5001
The justfile does not parse. just would refuse to run any recipe in it: a string or backtick is not closed, a recipe header has no :, an escape sequence such as \q is not one just knows, or a line is indented outside a recipe.
version := "1.0 # SL5001SL5002
A dependency or alias names a recipe that does not exist. The name is looked up in the justfile, its imports and, for module::recipe, in the module's own file.
build: compile # SL5002
cargo buildSL5003
An expression uses a variable or parameter that is not defined. Inside a recipe, its parameters come first, then the variables of the justfile and its imports, then just's own constants such as HEX.
greet:
echo {{name}} # SL5003SL5004
A function that does not exist is called. It is neither one of just's built-in functions nor a function defined with name(args) := ....
shout := upper("hi") # SL5004SL5005
A function is called with the wrong number of arguments.
path := replace("a/b", "/") # SL5005SL5006
A dependency passes the wrong number of arguments. A bare dependency passes none, (recipe a b) passes two, and the recipe must accept that many given its defaults and variadic parameter. A mapped dependency *(recipe ...) also needs a starred argument to map over.
test target:
cargo test {{target}}
ci: test # SL5006SL5007
A setting that just does not know is set.
set export-all # SL5007SL5008
An attribute that just does not know is used.
[hidden] # SL5008
build:
cargo buildSL5009
Two recipes have the same name. Unless set allow-duplicate-recipes is on, just refuses the justfile. Recipes enabled on different systems, such as one with [linux] and one with [macos], do not clash; [unix] covers Linux, macOS and the BSDs.
build:
cargo build
build: # SL5009
makeSL5010
A variable is assigned twice. Unless set allow-duplicate-variables is on, just refuses the justfile.
mode := "debug"
mode := "release" # SL5010SL5011
An alias clashes with another alias or a recipe of the same name.
alias b := build
alias b := bench # SL5011
build:
bench:SL5012
Recipes or variables depend on themselves. A recipe that is its own dependency, directly or through others, and a variable defined in terms of itself, cannot be run or evaluated.
a: b # SL5012
b: a # SL5012SL5013
A recipe parameter is never used. Nothing in the recipe's body, dependencies or defaults refers to it, neither as {{name}} nor, when it is exported with $name, as $name in a shell recipe. Recipes that receive their arguments as positional parameters (set positional-arguments or [positional-arguments]) are left alone.
deploy target: # SL5013
./deploy.shSL5014
A variable is never used. No recipe, dependency or other variable refers to it. Exported variables are left alone because the shell may read them, and so are variables whose names start with _.
unused := "x" # SL5014
build:
cargo buildSL5015
A setting is set twice.
set quiet
set quiet # SL5015SL5016
A setting has a value just refuses. Boolean settings take true or false, settings that name a command such as shell take a list like ['bash', '-c'], and the others take a string. indentation and minimum-version take a plain string literal: spaces or tabs for the indentation, and a MAJOR.MINOR.PATCH version no newer than just 1.58.0.
set shell := "bash" # SL5016SL5017
A path names a module that does not exist. No mod statement declares the first part of module::recipe.
release: tools::build # SL5017SL5018
An imported file or module source file is not found. import 'path' is resolved relative to the justfile that contains it, and mod name looks for name.just, name/mod.just and name/justfile. import? and mod? make the file optional.
import 'ci/release.just' # SL5018SL5019
A recipe's parameters are in an order just refuses. A parameter is listed twice, a parameter without a default follows one with a default, or a parameter follows the variadic + or * parameter, which must come last.
test target="all" filter: # SL5019
cargo test {{target}} {{filter}}SL5020
An attribute is used in a way just refuses. It is given the wrong number of arguments, a key it does not know, a key twice or a value it does not take, it is repeated or put on an item that cannot carry it, [cache] or [extension] is put on a recipe that runs line by line, or an [arg] names a parameter the recipe lacks, an option another parameter already uses, or an invalid option name, count or pattern.
[group] # SL5020
build:
cargo buildSL5021
A recipe line is indented differently from the recipe's first line. just requires every line of a recipe to start with the same whitespace, all tabs or all spaces. A line-by-line recipe may not be indented further either, except for a line continued from the one above with \; start the recipe with a shebang or give it [script] to write a multi-line shell construct.
check:
if true; then
echo yes # SL5021
fiSL5022
A deprecated function or setting is used. The message names its replacement, such as env(key) for env_var(key).
home := env_var("HOME") # SL5022SL5023
A feature is used without the setting it needs. Lists, ++, !, &&, || and mapped dependencies need set lists, which like user-defined functions also needs set unstable.
targets := ["a", "b"] # SL5023SL5024
A recipe depends on an absent module. When mod? finds no file for a module, just leaves out every recipe and alias that depends on one of its recipes, directly or through other recipes, so running them fails with "depends on absent module".
mod? tools
lint: tools::check # SL5024
echo lintedSL5025
Two user-defined functions have the same name. just refuses the justfile whatever their parameters, and neither allow-duplicate-recipes nor allow-duplicate-variables permits it. Functions enabled on different systems, such as one with [linux] and one with [macos], do not clash, and a function may share its name with a recipe, a variable or a built-in function.
set unstable
greet(name) := "hello " + name
greet(name) := "hi " + name # SL5025SL5026
A compile-time value runs a backtick or calls a function. Settings just reads before running anything, such as shell, tempdir, working-directory and the dotenv-* paths, and the [doc] attribute and [arg]'s help and pattern, cannot call a backtick or a function or read a variable that does, however indirectly. Only the branch of an if that is taken counts, and || and && stop as just's evaluator does. just checks this only for items enabled on the system it runs on; shell-lsp checks it for every system.
set tempdir := `mktemp -d` # SL5026SL6001
The Makefile does not parse. make stops with "missing separator": a line is neither a rule, an assignment nor a directive, which is most often a word on a line of its own or a rule whose : is missing.
all # SL6001
echo allSL6002
A conditional is not balanced. An else or endif has no ifeq, ifneq, ifdef or ifndef before it, a conditional is still open at the end of the file, which is reported on the last line like make does, or an ifeq does not have its two arguments.
CFLAGS = -O2
endif # SL6002SL6003
A define has no endef, or an endef has no define.
define HELP # SL6003
usage: make allSL6004
A recipe line starts with spaces instead of a tab. make reads recipe lines only when they start with a tab, or with the character set by .RECIPEPREFIX; a line starting with spaces after a rule is a syntax error.
all:
echo all # SL6004SL6005
A recipe line comes before any rule. A line starting with a tab is a recipe line, but no target is being defined yet.
echo hello # SL6005
all:
echo allSL6006
A variable is used but never set. The variable is not assigned in the Makefile or the files it includes, and it is not one of make's built-in variables such as CC or MAKE. It may still come from the environment or the command line, which is why this is only information.
all:
$(CC) -o app $(SOURCES) # SL6006SL6007
A recursively expanded variable refers to itself. VAR = $(VAR) more makes make expand the variable forever and stop as soon as something uses it; use += or := instead. A reference after an $(eval VAR := ...) that redefines the variable reads the new definition, and definitions in different branches of one conditional never meet, so neither is circular.
CFLAGS = $(CFLAGS) -O2 # SL6007
all:
cc $(CFLAGS) main.cSL6008
A .PHONY target has no rule. The name is probably misspelt, or the rule was removed. A phony target that another rule depends on, such as a FORCE prerequisite, needs no rule and is left alone.
.PHONY: all clena # SL6008
all:
@echo allSL6009
A target gets a second recipe. make warns that the later recipe overrides the earlier one and uses only the last. Double-colon rules (target::) are meant to have several, and recipes in different branches of one conditional never meet, so both are left alone.
all:
@echo one
all: # SL6009
@echo twoSL6010
A function make does not know is called. $(name args) with a space calls a function, and make has no function by that name; the expansion is empty.
FILES := $(wild *.c) # SL6010SL6011
A built-in function gets the wrong number of arguments.
OBJS := $(subst .c,.o) # SL6011SL6012
A variable reference is not closed. $( or ${ has no matching ) or } on the same logical line, in text make expands: a rule, a recipe, an immediate assignment or a recursive variable that something uses.
all:
echo $(CFLAGS # SL6012SL6013
An included Makefile is not found. include looks for the file relative to the directory make runs in; -include and sinclude make it optional.
include config.mk # SL6013SL6014
A variable is set but never used. Nothing in the Makefile or the files it includes expands it. Exported variables, variables make itself reads such as CFLAGS or SHELL, and variables used by name with $(call ...), $(value ...) or $(origin ...) are left alone.
VERSION := 1.0 # SL6014
all:
@echo allSL6015
A deferred variable reference is not closed. A recursively expanded value (=, ?=, += or define), or the recipe of a pattern rule, has a $( or ${ without its closing parenthesis. make reads the file fine and fails only when it expands the variable or uses the pattern rule; once something expands the variable, the reference is reported as SL6012.
SEARCH = -I$(INCLUDE # SL6015
all:
@echo doneSL6016
A target does not match its static pattern. In targets: pattern: prerequisites, every target must match the target pattern. make ignores a target that does not, so its recipe never runs.
main.o util.c: %.o: %.c # SL6016
cc -c $< -o $@SL6017
A standard target is missing from .PHONY. Targets such as clean, install, check or dist name an action, not a file. If a file or directory of that name exists, make considers the target up to date and never runs its recipe; listing the target in .PHONY prevents that. A recipe that creates $@ is left alone.
clean: # SL6017
rm -f appSL7001
The Dockerfile does not parse. BuildKit refuses to build it: a parser directive, a flag, a JSON array or a heredoc is malformed, an instruction lacks the arguments it needs, or the image of a FROM or COPY --from is no valid reference once its build arguments are expanded.
# SL7001
FROM alpine ASSL7002
An instruction is not one BuildKit knows. The first word of every instruction must be one of FROM, RUN, COPY, ADD, ENV, ARG and the other Dockerfile instructions; anything else stops the build.
FROM alpine
# SL7002
RUNN echo hiSL7003
A flag is not one the instruction takes. BuildKit stops at a flag the instruction does not accept, such as --chown on RUN.
FROM alpine
# SL7003
RUN --chown=1000 echo hiSL7004
CMD or ENTRYPOINT uses the shell form. The shell form runs the command under /bin/sh -c, which becomes PID 1 and does not pass signals such as SIGTERM on, so the container cannot shut down cleanly. Write the command as a JSON array. A SHELL earlier in the stage or its base stages turns the check off, as BuildKit does.
FROM alpine
# SL7004
CMD ./server --port 80SL7005
COPY --from names a stage that does not exist. Without a stage of that name Docker pulls an image called that, which is rarely what a misspelt stage name meant. A name that a bake file (docker-bake.hcl, docker-bake.json or any *.hcl with target blocks) or a Compose additional_contexts maps to a named context for this Dockerfile is not reported, since the build reads that context instead; how bake files are found and read is described under Named contexts. When that context is a docker-image:// reference without a tag, DL3006 is reported on the name instead.
FROM golang:1.23 AS build
FROM alpine
# SL7005
COPY --from=buidl /out/app /appSL7006
A variable is used but never declared. Build arguments must be declared with ARG before they are used, those in FROM before the first FROM, and positional parameters such as $1 never have a value outside RUN.
FROM alpine
# SL7006
WORKDIR /srv/$APPSL7007
Two stages have the same name. Stage names should be unique; COPY --from picks the last stage of that name while FROM picks the closest one before it.
FROM alpine AS base
# SL7007
FROM debian AS baseSL7008
A build argument is declared but never used. Nothing in the Dockerfile reads it and no RUN comes after it in the stage, whose programs could read it from the environment. BuildKit's own BUILDKIT_ arguments are left alone.
FROM alpine
RUN echo hi
# SL7008
ARG UNUSED=1
COPY app /appSL7009
A stage name is not lowercase. Stage names are case-insensitive, and BuildKit asks for lowercase names so that every reference to a stage looks the same.
# SL7009
FROM alpine AS BuildSL7010
AS does not match the casing of FROM. Write FROM … AS or from … as, not a mix.
# SL7010
FROM alpine as buildSL7011
An empty line continues an instruction. An empty line after a line ending in the escape character is swallowed into the instruction; a later BuildKit will treat it as an error.
FROM alpine
RUN apk add \
# SL7011
curlSL7012
An instruction is not cased like the others. Instructions are case-insensitive, but a Dockerfile should use one casing; the minority is reported, and a tie counts as uppercase. Instructions that ONBUILD triggers do not count.
FROM alpine
# SL7012
run echo hiSL7013
A stage uses a reserved name. scratch and context have their own meaning in FROM and --from, so a stage must not take them.
# SL7013
FROM alpine AS scratchSL7014
MAINTAINER is deprecated. Set the org.opencontainers.image.authors label instead.
FROM alpine
# SL7014
MAINTAINER me@example.comSL7015
WORKDIR is relative before the stage sets one. A relative WORKDIR resolves against the working directory of the base image, which can change under it. Once any WORKDIR has been set in the stage or its base stages, relative ones are fine.
FROM alpine
# SL7015
WORKDIR appSL7016
A stage has more than one CMD, ENTRYPOINT or HEALTHCHECK. Only the last one takes effect, so the earlier ones are dead.
FROM alpine
# SL7016
CMD ["one"]
CMD ["two"]SL7017
ENV or LABEL uses the legacy key value form. The form without = sets a single key whose value is the rest of the line; write key=value.
FROM alpine
# SL7017
ENV MODE productionSL7018
A secret is passed in ARG or ENV. Build arguments and environment variables end up in the image metadata and history. Names that contain a word such as TOKEN, PASSWORD or SECRET should come from a secret mount instead.
FROM alpine
# SL7018
ARG API_TOKENSL7019
EXPOSE gives the protocol in uppercase. The protocol after the port is tcp or udp, in lowercase.
FROM alpine
# SL7019
EXPOSE 53/UDPSL7020
EXPOSE maps a host port. EXPOSE only documents the container port; publishing it on a host port is a docker run -p decision.
FROM alpine
# SL7020
EXPOSE 8080:80SL7021
The default of a build argument leaves a FROM image empty. Without a --build-arg the image name expands to nothing and the build fails; give the argument a default.
ARG BASE=
# SL7021
FROM $BASESL7022
FROM --platform is a constant. A fixed platform pins the base image to one architecture, which breaks multi-platform builds; use $BUILDPLATFORM or $TARGETPLATFORM.
# SL7022
FROM --platform=linux/amd64 alpineSL7023
FROM --platform=$TARGETPLATFORM is redundant. Stages build for the target platform already.
# SL7023
FROM --platform=$TARGETPLATFORM alpineSL7024
COPY --from names a stage that is not built before it. A stage can only copy from a stage defined earlier in the Dockerfile, never from itself or a later one.
FROM alpine AS build
# SL7024
COPY --from=final /app /app
FROM alpine AS finalNix files
shell-lsp reads the whole Nix file: it resolves every name to its binding and finds the shell strings in it. The parser keeps going after an error, and the shell strings elsewhere in the file stay checked, but the checks below other than SL8001 wait for a file that parses, since a broken file says too little about which names exist.
lint.exclude turns a check off like any other, and lint.profile applies: minimal keeps the errors and warnings. # shellcheck disable= works as it does in a shell script, in # comments: before the first expression it covers the file, after code it covers that line up to the comment, and on a line of its own it covers the binding, formal, list element or other expression that starts next. With nothing to cover, as in front of in or a closing bracket, it does nothing. It takes codes, ranges such as SL8000-SL8099 and all. SL8001 cannot be disabled this way. See statix and deadnix compatibility for statix.toml, # deadnix: skip and how the options of those tools map here.
SL8001
The Nix file does not parse. Nix would refuse to evaluate it: a bracket or string is not closed, a binding has no ;, an operator has no operand, or an expression is nested too deeply to analyse.
{ version = ; } # SL8001SL8002
A variable has no binding. No enclosing let, rec, function argument or with can provide the name, and it is not a built-in, so Nix refuses the file before evaluating anything. Inside a with nothing is reported, since the name can only be known at evaluation. Global built-ins such as map take precedence over a with, and any lexical binding takes precedence over both.
{ pname = "x"; version = versoin; } # SL8002SL8003
An attribute is defined twice. Nix refuses the file. Paths that only share a prefix merge, and so do attribute sets written for the same name, as a.b = 1; a.c = 2; or a = { b = 1; }; a = { c = 2; }; do. A dynamic name such as ${x} is only known when the file is evaluated and is not compared; a constant one such as ${"a"} is the name a.
{
a = 1;
a = 2; # SL8003
}SL8004
A function pattern names an argument twice. Repeating the @ name in the pattern counts too. Nix refuses the file. The quick fix removes a repeated formal.
{ a, a }: a # SL8004SL8005
A let binding is never read. Nix is lazy, so an unread binding is never evaluated, and removing it changes nothing. A binding read only by itself, or only by other bindings of the same let that nothing reads, counts as unread, so a and b are both reported in let a = 1; b = a; in 2. Names starting with _ are SL8029. __sub, __mul, __div, __lessThan, __findFile and __nixPath are left alone, since Nix reads them itself when it evaluates -, *, /, comparisons and <path> lookups. The fix removes the binding, with every line of a dotted one, or the one name from an inherit.
let unused = 1; in 2 # SL8005SL8006
A function never reads its argument or its @ name. Removing a plain argument would change how the function is called, so the quick fix renames it with a _ prefix, which is also how to say the argument is meant to go unread, as for the first argument of an overlay. An unread @ name can simply go, and the fix-all action removes it.
x: 1 # SL8006SL8007
A function pattern names an argument it never reads. A formal read only by the default of another unread formal counts as unread. With ... and no @ name in use the fix-all action removes the formal, since callers can still pass it. Without ... removing it makes those callers fail, and with an @ name in use the formal may state what the set passed on must hold, so there the quick fix is offered only on request. Names starting with _ are SL8029. The outputs of a flake is exempt without ..., since Nix calls it with every input whether it reads them or not; SL8038 reports the inputs nothing reads.
{ a, b, ... }: a # SL8007SL8008
Parentheses change nothing. They enclose a single value, or a whole expression where any expression may stand: a binding's value, a function body, a condition. They are not reported where taking them away would join tokens, as in a/(b) or x:(y), where (a.b).c or d would look at a different attribute path, around a path or a number before ., or around the source of inherit (x) y;, where they are required. Parentheses that only make an operator's precedence plain are left alone.
{ a = (1); } # SL8008SL8009
An if picks between true and false. if x then true else false is x and if x then false else true is !x. A name true or false bound in the file is not the Boolean, and is left alone. x == true and x == null are not reported: both also accept values that are not Booleans, so they say more than x does.
x: if x then true else false # SL8009SL8010
rec has nothing to do. No expression in the set reads any of its attributes, so it means the same without rec. A rec set that defines __overrides is left alone, since Nix reads that attribute itself. A rec on a set written for a name that an earlier set already defined never takes effect at all.
rec { a = 1; } # SL8010SL8011
x = x; in a set that is not recursive is inherit x;. In a let or a rec set the same words mean a binding that reads itself, which is a different thing and not reported.
x: { x = x; } # SL8011SL8012
or is used as a variable. Nix still reads f or as f applied to a variable named or, in this one position, and warns that this will change. It is usually a .attr or default missing its attribute. Rename the binding.
let or = 1; f = x: x; in f or # SL8012SL8013
A let binds nothing. let in x is x. This is statix's empty_let_in.
let in 1 # SL8013SL8014
An antiquotation reaches a command's arguments unescaped. This check is optional and off by default; turn it on with enable=unescaped-antiquotations in .shellcheckrc, --enable=unescaped-antiquotations or the lint.optional setting. A ${x} in a string that is shell becomes text before the shell parses it, so a space, quote or $ in its value changes the command. Use lib.escapeShellArg, or lib.escapeShellArgs for a list. The shell's own parse decides where it applies: only a hole inside a word that is an argument of a command is reported, never a hole that is a whole statement or the command word, which is how code is spliced on purpose, and never one in an assignment, a loop list, a comment or a here-document. The value must also not be provably safe: a store path (pkgs.x, a path, the result of a writer, lib.getExe, lib.getBin, lib.makeBinPath), a number, a literal that holds no character the shell treats specially, or an expression that is escaped already. A value followed by a / counts as a path.
cfg: writeShellScript "x" ''
cat ${cfg.dir} # SL8014
''SL8015
Two Boolean literals are compared. true == false is known without evaluating anything. The fix writes the answer. A name true bound in the file is not the literal, and is left alone. x == true is not reported, as for SL8009. This is statix's bool_comparison.
true == false # SL8015SL8016
a = b.a; is inherit (b) a;. The binding's name and the one attribute selected are the same, so the inherit form says it once. Both forms read b from the same scope, in a let and a rec as well, so the fix changes nothing. A longer path such as a = b.c.a;, or a selection with or, is left alone. This is statix's manual_inherit_from.
b: { a = b.a; } # SL8016SL8017
let { ... } is an undocumented form. Nix reads it as a rec set with .body selected, and that is what the fix writes. This is statix's legacy_let_syntax.
let { body = 1; } # SL8017SL8018
A let is the whole body of another. The two can be one block. It is not reported when they cannot: when both bind a name, when the outer bindings read a name the inner block would then capture, or when the inner block binds a name Nix reads itself, such as __sub. This is statix's collapsible_let_in.
let a = 1; in let b = 2; in a + b # SL8018SL8019
A function only passes its argument on. x: f x is f. This check is optional and off by default, since the long form is often clearer; turn it on with enable=eta-reduction. The fix is offered on request only: f may be a value that is not yet a function, and f is evaluated earlier once the wrapper is gone, which can turn laziness into a recursion when two bindings refer to each other. A binding whose own value it is, as in f = x: f x, is never reported, since f = f recurses forever. This is statix's eta_reduction.
f: x: f x # SL8019SL8020
A pattern names nothing. { ... }: 1 and { }: 1 read no attribute, and _ says so. This check is optional and off by default, since { ... }: is the usual shape of a NixOS module; turn it on with enable=empty-pattern. A function whose body is a set that sets imports is left alone, as statix does. The fix is offered on request only: _: also accepts arguments that are not sets. This is statix's empty_pattern.
{ ... }: 1 # SL8020SL8021
x@{ ... } captures nothing that x does not. The fix is offered on request only, since { ... } also makes the function refuse an argument that is not a set. This is statix's redundant_pattern_bind.
x@{ ... }: x # SL8021SL8022
A URI is not quoted. A bare URI is a string spelled in a form that RFC 45 deprecates, and the fix quotes it. This is statix's unquoted_uri.
{ a = https://example.org; } # SL8022SL8023
builtins.toPath is deprecated. To make a path from a string, add it to one: /. + s. To keep a string, use it as it is. There is no automatic fix, because which of those is meant depends on the code. A toPath bound in the file, or reached through a with that is not builtins, is left alone. This is statix's deprecated_to_path.
builtins.toPath "/x" # SL8023SL8024
!(a == b) is a != b. The fix keeps the parentheses where the operand of a tighter operator needs them, as in (a != b) == c. This is statix's bool_simplification.
!(1 == 2) # SL8024SL8025
if x ? a then x.a else y is x.a or y. Both yield y when x lacks a, and when x is not a set. The fix parenthesizes the default unless it is a single value. This is statix's useless_has_attr.
x: if x ? a then x.a else 1 # SL8025SL8026
Three or more bindings in a set start with the same key. One nested set could hold them. This is a matter of style and has no automatic fix, so the check is optional and off by default; turn it on with enable=repeated-keys. It looks at sets that are not rec, and is not reported when the first binding of the key is already a whole a = { }. This is statix's repeated_keys.
{ a.b = 1; a.c = 2; a.d = 3; } # SL8026SL8027
A list is joined with an empty list. [ ] ++ x is x. This is statix's empty_list_concat.
x: [ ] ++ x # SL8027SL8028
An inherit names no attribute. It has no effect at all, not even evaluating its source. This is statix's empty_inherit, which reports only the form without a source.
{ inherit; } # SL8028SL8029
A let binding or a pattern name starting with _ is never read. The _ says the name goes unread, but in a let the binding itself can go, and a name in a pattern is part of what the function asks for. This matches deadnix. To leave these names alone, as deadnix --no-underscore does, exclude SL8029. A plain argument such as _x: 1 is how to say an argument goes unread, and is never reported.
let _unused = 1; in 2 # SL8029SL8030
A name starting with _ is read. The _ says it goes unread, so one of the two is wrong. This check is optional and off by default, as deadnix --warn-used-underscore is; turn it on with enable=used-underscore-bindings. Plain arguments and rec attributes are left alone, as deadnix leaves them.
let _a = 1; in _a # SL8030SL8031
A flake reads something a pure evaluation does not have. <nixpkgs>, builtins.currentSystem and builtins.currentTime fail, and builtins.getEnv and builtins.nixPath silently yield nothing, unless the flake is evaluated with --impure. Only flake.nix-shaped files are looked at: a set of description, inputs, outputs and nixConfig, whose outputs is a function.
{ outputs = { self }: { system = builtins.currentSystem; }; } # SL8031SL8032
A fetcher has nothing that pins what it fetches. builtins.fetchTarball, builtins.fetchurl and builtins.fetchGit given only a URL fetch whatever is there today and fail in a pure evaluation. Add sha256, or for fetchGit a rev. Only an argument written out in place is judged.
builtins.fetchTarball "https://example.org/a.tar.gz" # SL8032SL8033
// overrides an attribute that a rec set reads itself. In rec { a = 1; b = a; } // { a = 2; }, b is still 1, because rec resolved it before // ran. Merge the sets, or use a fixed point such as lib.fix.
(rec { a = 1; b = a; } // {
a = 2; # SL8033
}).bSL8034
A NixOS module chooses its own shape from config. config = if config.x then ... and imports = lib.optional config.x ... recurse forever: the module system must read every module's attributes and imports to compute config. Use lib.mkIf for config, whose condition the module system can defer, and for imports import unconditionally and switch the imported module's effect with an option. The check looks at the if, lib.optional and lib.optionals of a module's top level, and at a condition that is certain to read config, directly or through a let binding. Values under other attributes, which the module system reads lazily, are left alone. Where the else is { } and lib is in scope, the fix writes lib.mkIf on request.
{ config, ... }: {
config = if config.x then { } else { }; # SL8034
}SL8035
A with wraps a whole file. Every free name in the file may then come from it, so a misspelt name is no longer reported, and a name bound outside the with beats one in it without any sign. This check is optional and off by default; turn it on with enable=top-level-with.
{ lib }: with lib; id # SL8035SL8036
A path is interpolated. "${./src}" copies the path, all of it, into the Nix store, and yields the copy's name. That is often the point, but for a directory it may be a lot of copying, and toString or + keeps the path. This check is optional and off by default; turn it on with enable=store-copied-paths.
"${./.}" # SL8036SL8037
pkgs.lib is written where lib is in scope. This check is optional and off by default, since a module's lib argument can be extended beyond pkgs.lib; turn it on with enable=pkgs-lib. For the same reason the fix is offered on request only.
{ pkgs, lib }: pkgs.lib.id lib # SL8037SL8038
A flake declares an input nothing reads. No read of the outputs argument and no follows reaches it, so it only slows down locking. Nothing is reported when the inputs could be read in a way the file does not show: when the @ name of outputs or self is passed on whole, or self.inputs is read.
{
inputs.unused.url = "github:a/b"; # SL8038
outputs = { self, ... }: { };
}SL8039
A flake overrides an input that its input does not have. Nix warns that the override does nothing, and flake.lock shows it: the locked a lists no input b. This looks at flake.lock next to flake.nix, through the same cache as the configuration files, and says nothing when there is no lock file or the input is not locked yet.
{
inputs.a.url = "github:o/a";
inputs.a.inputs.gone.follows = "b"; # SL8039
inputs.b.url = "github:o/b";
outputs = { self, a, b }: { };
}SL8040
A flake input locks its own nixpkgs. The flake then evaluates two copies of nixpkgs. inputs.a.inputs.nixpkgs.follows = "nixpkgs"; shares one, if the input works with that revision, which only its author can promise. So this check is optional and off by default; turn it on with enable=missing-nixpkgs-follows.
{
inputs.nixpkgs.url = "github:NixOS/nixpkgs";
inputs.a.url = "github:o/a"; # SL8040
outputs = { self, nixpkgs, a }: { };
}statix and deadnix compatibility
Every lint of statix has a check above, and deadnix's findings are SL8005, SL8006, SL8007 and SL8029.
| statix lint | Check | Fix | By default |
|---|---|---|---|
bool_comparison (W01) | SL8015 | safe | on |
empty_let_in (W02) | SL8013 | safe | on |
manual_inherit (W03) | SL8011 | safe | on |
manual_inherit_from (W04) | SL8016 | safe | on |
legacy_let_syntax (W05) | SL8017 | safe | on |
collapsible_let_in (W06) | SL8018 | safe | on |
eta_reduction (W07) | SL8019 | on request | off |
useless_parens (W08) | SL8008 | safe | on |
empty_pattern (W10) | SL8020 | on request | off |
redundant_pattern_bind (W11) | SL8021 | on request | on |
unquoted_uri (W12) | SL8022 | safe | on |
empty_inherit (W14) | SL8028 | safe | on |
deprecated_to_path (W17) | SL8023 | none | on |
bool_simplification (W18) | SL8024 | safe | on |
useless_has_attr (W19) | SL8025 | safe | on |
repeated_keys (W20) | SL8026 | none | off |
empty_list_concat (W23) | SL8027 | safe | on |
| deadnix option | Here |
|---|---|
--no-lambda-arg | exclude SL8006 |
--no-lambda-pattern-names | exclude SL8007 |
--no-underscore | exclude SL8029 |
--warn-used-underscore | enable=used-underscore-bindings (SL8030) |
--edit | the fix-all code action, or shell-lsp check -f diff for a patch |
--output-format json | shell-lsp check -f json |
--no-lambda-arg and SL8006 differ in one way: SL8006 also covers an unread @ name, which deadnix reports whatever its options. deadnix --edit also removes a formal from a pattern without ...; that makes existing callers fail, so here the fix is on request.
Where the tools are wrong, shell-lsp differs on purpose, with corpus/nix-lint.md keeping the count:
- statix reports
let a = a; in aandrec { a = a; }asmanual_inherit;inherit a;would read an outerainstead, so SL8011 does not. - statix reports
(a.b).c or d;a.b.c or dyieldsdwhere the original fails, so SL8008 does not. SL8008 also reports parentheses around a whole expression in places statix does not look, such as anifcondition and a function's default. - statix's fix for
!(a == b) == cdoes not parse, and for!(a == b) // cmeans something else; SL8024's fix keeps the parentheses. - statix reports
let a = 1; in let a = 2; in aas collapsible; merging is an error, so SL8018 does not. - deadnix counts
inherit (x) a;as reading theaof an enclosing pattern; it reads onlyx, so SL8007 reports thata. - deadnix reports
let __sub = f; in 2 - 3; Nix calls that binding for-. - deadnix reports the formals of a flake's
outputswithout...; without them Nix refuses the call. - deadnix does not report
let a = b; b = a; in 2; SL8005 does.
statix.toml
The nearest statix.toml in the file's directory or above is read, through the same cache as .shellcheckrc. disabled turns the named lints off in Nix files. Unknown names are ignored, as statix ignores them. ignore lists patterns in .gitignore syntax, relative to the file's directory, for files in which all of the checks above from statix are off. nix_version is accepted and has no effect, since none of statix's lints depends on it any more. Other keys are ignored and a file that is not TOML is reported, as statix does.
disabled = ["repeated_keys"]
ignore = [".direnv", "generated.nix"]Skip comments
A comment containing deadnix: skip silences SL8005, SL8006, SL8007, SL8029 and SL8030 for what follows it on its own line and on the next line, as deadnix does: a blank line or another comment in between ends it, and a one-line let under it is covered whole. Either comment kind works. A comment containing statix: skip or statix skip does the same for the checks from statix. statix itself reads no such comment, so this exists for files that want a single spelling across tools.