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.
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.
cat > clean.sh <<'EOF'
#!/bin/bash
dir=$1
for f in $dir/*.log; do
rm $f
done
EOF
shellcheck clean.sh
echo "exit: $?"
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: 1ShellCheck 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.