Linux Basic — Commenting Best Practices
Commenting Best Practices
Good comments explain why you made a choice, not what the code does (the code already says that).
The Golden Rule
Comment the intent, not the implementation.
# BAD — obvious from the code
# loop through files
for f in *.log; do
# GOOD — explains the business rule
# process only logs from the last 7 days (compliance requirement)
for f in *.log; do
When to Comment
| Situation | Comment? |
|---|---|
| Non-obvious algorithm or workaround | Yes — explain why it’s weird |
| Hardcoded magic value | Yes — source and rationale |
| Complex regex or math | Yes — plain-English translation |
Standard idiom (set -euo pipefail) |
No — readers know it |
| Variable assignment | No — the name should be clear |
| TODO / FIXME / HACK | Yes — with a ticket number |
Examples
Magic numbers
# retry interval based on SLA — see ticket INFRA-4231
readonly RETRY_INTERVAL=300
Workaround
# GNU date has no --iso-8601 on macOS; use +%F instead
date +%F
Complex logic
# if both day and weekday match, cron runs (OR, not AND)
# so we explicitly check day != Sunday to avoid double-runs
if [[ $(date +%u) -ne 7 ]]; then
weekly_report
fi
TODOs and FIXMEs
Always include context:
# TODO(alice): switch to rsync --fuzzy once infra upgrades to rsync 3.1+
# FIXME: this breaks if filename has spaces — see issue #42
# HACK: sleep 1 works around race in upstream lib (v2.3.1)
Grep for these during code review.
Inline Comments (Use Sparingly)
process_file "$f" & # background to parallelise
wait # sync before cleanup
Only when the line itself is cryptic and renaming doesn’t help.
Header Comment
Every script should start with a brief description. See the next page for the full header template.
Next → Script Header Block