ShellCheck Bash Script: Find Bugs and Security Issues in Linux

Quick Linux Tip #128:

Question: How do I lint my bash scripts for bugs and security issues?

Try: shellcheck /opt/scripts/backup.sh

Info: Static analysis tool that catches common bugs, security flaws, and style issues in shell scripts.

Examples:

  • $ shellcheck -s bash *.sh  # Force the shell dialect to bash explicitly
  • $ shellcheck -f gcc script.sh  # Generate compiler-style output tailored for text editors
  • $ find . -name '*.sh' -exec shellcheck {} +  # Recursively lint all shell scripts across a directory

Note: Install via sudo apt install shellcheck. Specific rule numbers (e.g., SC2086) make it easy to look up solutions online. Integrate into CI/CD pipelines to catch bugs before code reaches production.




LinuxTeck.com
linuxteck:~$ shellcheck /opt/scripts/backup.sh

In backup.sh line 5:
if [ $USER = "root" ]; then
     ^-- SC2086 (info): Double quote to prevent globbing and word splitting.
     ^-- SC2170 (warning): Numerical comparator forced. Use '=' to compare strings.

In backup.sh line 12:
for file in $(ls /data/*.log); do
     ^-- SC2045 (warning): Iterating over ls output is fragile. Use globs.

In backup.sh line 18:
rm -rf $TARGET_DIR/*
     ^-- SC2086 (info): Double quote to prevent globbing and word splitting.
     ^-- SC2115 (warning): Use "${var:?}" to ensure this never expands to /*.

For more information:
https://www.shellcheck.net/wiki/SC2115 -- Use "${var:?}" to ensure this n...
https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbi...

linuxteck:~$

PREVIOUS ARTICLE Quick Linux Tip #127: Linux Process Stack Trace: Find Where a Hung Process Is Stuck NEXT ARTICLE Quick Linux Tip #129: Linux Network Namespace: Create an Isolated Network Stack
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.