Skip to content
shellhacks.dev
Testing

Run ShellCheck on a script

Run shellcheck on a script and read each finding: the line, the code such as SC2086 and a fix. The exit status is non-zero, so it can gate CI.

2 min read
Summarize in AI

A script works on your files and breaks on one with a space in the name, and you want a tool to find that class of mistake.

Shell
cat > clean.sh <<'EOF'
#!/bin/bash
dir=$1
for f in $dir/*.log; do
  rm $f
done
EOF
shellcheck clean.sh
echo "exit: $?"
Text

In clean.sh line 3:
for f in $dir/*.log; do
         ^--^ SC2231 (info): Quote expansions in this for loop glob to prevent wordsplitting, e.g. "$dir"/*.txt .


In clean.sh line 4:
  rm $f
     ^-- SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean:
  rm "$f"

For more information:
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
  https://www.shellcheck.net/wiki/SC2231 -- Quote expansions in this for loop...
exit: 1

ShellCheck parses the script and reports each pattern that is risky or wrong, with the line, the SC code and a message. The unquoted $f triggers SC2086, which explains that the value is subject to word splitting and globbing, and the glob in the for line triggers a related check, SC2231. The wiki page for every code shows a failing and a fixed example. The exit status is 1 when any finding is reported, so a pipeline stops on it.

ShellCheck reads the shell from the shebang line, and without one it needs -s bash or -s sh. It cannot see what the data contains at run time, so a clean report is not a proof of safety. This output is from ShellCheck 0.9.0, and new releases add checks that may flag old scripts.

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.