Skip to content
shellhacks.dev
Testing

Output ShellCheck in diff format

Have ShellCheck write a fix as a patch with -f diff and apply it with patch -p1. It only offers fixes for findings that have one, like missing quotes.

1 min read
Summarize in AI

ShellCheck reports forty missing quotes, and you would rather apply the fix than retype each one.

Shell
printf '#!/bin/bash\nname=$1\necho $name\n' > fix.sh
shellcheck -f diff fix.sh
echo ---
shellcheck -f diff fix.sh | patch -p1
cat fix.sh
shellcheck fix.sh && echo "clean"
Text
--- a/fix.sh
+++ b/fix.sh
@@ -1,3 +1,3 @@
 #!/bin/bash
 name=$1
-echo $name
+echo "$name"

---
patching file fix.sh
#!/bin/bash
name=$1
echo "$name"
clean

-f diff prints a unified diff of the changes ShellCheck knows how to make, with a/ and b/ path prefixes, so patch -p1 or git apply can apply it. Here the single fix is the double quotes around the variable, which are the answer to SC2086 and the commonest finding. The format is listed in the ShellCheck manual. After patching, the plain run reports nothing.

Many findings have no automatic fix, so the diff covers only part of the report, and a second run shows what is left. Read the patch before applying it: a quote added around a variable that was meant to split into words changes what the script does. Commit first, so git diff shows exactly what was changed.

Share

More snippets

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
Testing

Check status in Bats

Check a command's exit code in Bats with run and $status. run never fails the test by itself, and Bats 1.5 added run -N to assert the status in one line.

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

Get new posts by email

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

Unsubscribe in one click. No spam, ever.