Comments, Style, and ShellCheck
Prerequisites: Quoting, Your first script
Comments
Everything after a # on a line is a comment (except the shebang on the
first line):
# Remove build output older than 7 days, keeping the latest release.
find build -type f -mtime +7 -not -name 'latest*' -delete # safe: build is regenerated
As always, explain why — especially for commands with many options, where the intent isn't obvious.
Style that prevents bugs
- Start scripts with
#!/usr/bin/env bash. - Quote every variable:
"$var". - Use
[[ ]]for tests and$(...)for command substitution. - Use lowercase names for your own variables.
- Indent consistently (two or four spaces) inside
if,for, and functions. - Give scripts a usage message and exit non-zero on errors.
ShellCheck
ShellCheck is a free linter that finds common shell bugs — unquoted variables, typos, commands that don't do what you think:
# illustrative
cat > example.sh <<'EOF'
#!/usr/bin/env bash
file=$1
rm $file
EOF
shellcheck example.sh
In example.sh line 3:
rm $file
^---^ SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean:
rm "$file"
Install it with your package manager (apt install shellcheck, brew install shellcheck), use it in your editor (the VS Code extension shows
warnings as you type), or paste scripts into shellcheck.net. Each warning
code links to an explanation — reading them is one of the fastest ways to
learn Bash's pitfalls.
What's next
You now know enough Bash to automate real tasks. Try the Beginner Projects, then continue to Level 2 — Intermediate, which starts with functions.