Skip to content
shellhacks.dev
Testing

Ignore a ShellCheck rule on one line

Silence one ShellCheck finding on one command with a directive comment, # shellcheck disable=SC2086, placed on the line above, and give a reason with it.

1 min read
Summarize in AI

ShellCheck is right in general and wrong for this line, where the unquoted expansion is deliberate.

Shell
cat > opts.sh <<'EOF'
#!/bin/bash
flags="-l -a"
ls $flags /tmp > /dev/null
# shellcheck disable=SC2086 # the flags are meant to split into separate words
ls $flags /tmp > /dev/null
EOF
shellcheck opts.sh
echo "exit: $?"
Text

In opts.sh line 3:
ls $flags /tmp > /dev/null
   ^----^ SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean:
ls "$flags" /tmp > /dev/null

For more information:
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
exit: 1

A comment of the form # shellcheck disable=CODE applies to the next command, as the directive documentation explains. Only the second ls is silenced, so the first still produces the finding, and the text after a second hash on the same comment is ignored by ShellCheck, which leaves room for the reason. A directive placed on its own line before a function covers the whole function.

A directive at the top of the file, before the first command, applies to the entire script, which hides real problems for good. Keep it narrow and write the reason, since the next reader cannot tell why the rule was turned off. An array, flags=(-l -a) with "${flags[@]}", removes the need for the directive in Bash.

Share

More snippets

Testing

Choose the shell for ShellCheck

Tell ShellCheck which shell a script targets with -s bash or -s sh. Without a shebang it cannot tell, and as sh it flags every Bash-only feature as SC3xxx.

2 min read
Testing

Skip a Bats test

Skip a Bats test with skip or skip "reason", which can be called in the middle of a test. A skipped test counts as passed, and the reason shows in the output.

2 min read
Testing

Load helpers in Bats

Share code between Bats tests with load helpers, which reads helpers.bash from the test file's directory. A plain source breaks when bats runs from elsewhere.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.