Skip to main content

Comments in Bash


Learning Focus
  1. Understand the role of comments in Bash scripting for readability and documentation.
  2. Learn the difference between single-line, inline, and multi-line comments.
  3. Use comments to temporarily disable code during testing or debugging.
  4. Apply structured commenting for WordPress VPS scripts.
  5. Implement metadata headers for maintainable automation.
  6. Avoid common commenting mistakes that break Bash scripts.

1. 5W + 1H Framework

ElementDescription
WhatComments are non-executable text used to describe or disable code in Bash scripts.
WhyThey improve script readability, maintainability, and debugging safety.
WhoBash users, WordPress administrators, and DevOps engineers managing VPS automation.
WhereBefore, beside, or around code blocks within .sh scripts or cron jobs.
WhenWhen explaining logic, marking TODOs, or preventing command execution temporarily.
HowUse # for single-line or inline comments, and : ' ... ' or <<COMMENT ... COMMENT for multi-line comments.

2. Prerequisites

  • Completed Module 1.4 (Running Scripts) and Module 1.5 (Shebang).
  • Able to execute Bash scripts with chmod +x script.sh.
  • Familiarity with WordPress CLI and Linux command syntax.

3. Core Syntax & Concept

NoSyntax FormulaTypeSyntax ExampleDescriptionOutput Behavior
1# [comment text]Single-Line Comment# This is a commentText after # is ignored by Bash.Not displayed/executed.
2[command] # [comment]Inline Commentecho "Hello" # prints greetingAdd notes beside active commands.Command executes; comment ignored.
3: ' [multi-line comment] 'Block Comment (colon method): ' Line 1 Line 2 'Multi-line block ignored by Bash.Entire section ignored.
4<<COMMENT ... COMMENTBlock Comment (Heredoc)<<COMMENT ... COMMENTAnother way to block-comment text.Ignored when unreferenced.
5# [disabled command]Disable Code# wp plugin update --allTurns active command into a comment.Command skipped.
6# Key: ValueMetadata Header`# Author: DonnyVersion: 1.0`Adds descriptive info to top of script.

4. Demonstration Example

Input Script:

#!/bin/bash
# WordPress Plugin Update Script
# Author: Donny Ari
# Date: 2025-10-09

echo "Starting plugin update..." # status message
# wp plugin update --all --path=/var/www/html
echo "✅ All plugins updated successfully."

Expected Output:

Starting plugin update...
✅ All plugins updated successfully.

Explanation: All lines beginning with # are ignored. Inline comments are also ignored by Bash, ensuring only valid commands execute.

5. Use Cases

5.1 Documenting Script Purpose

Input:

#!/bin/bash
# Purpose: Backup WordPress directory daily
# Location: /home/wpbackup/
tar -czf /home/wpbackup/backup_$(date +%F).tar.gz /var/www/html

Expected Output:

(no output unless echo is used)

Explanation: Header comments document the script’s purpose, path, and function. Use Case: Helps when auditing VPS scripts or during developer handovers.

5.2 Adding Inline Comments

Input:

echo "Compressing site..." # Prepare tarball backup
tar -czf /home/wpbackup/site_$(date +%F).tar.gz /var/www/html

Expected Output:

Compressing site...

Explanation: Inline comments clarify the purpose of commands. Use Case: Ideal for automation logs in shared WordPress maintenance scripts.

5.3 Multi-Line Block Comment

Input:

: '
The following lines are temporarily disabled:
wp plugin update --all
wp theme update --all
'
echo "Skipping updates during maintenance mode."

Expected Output:

Skipping updates during maintenance mode.

Explanation: Block comment syntax : ' ... ' disables multiple lines at once. Use Case: Temporarily pausing updates while testing new themes.

5.4 Disabling Code Safely

Input:

# wp option update blog_public 0
echo "🔒 Visibility change disabled for now."

Expected Output:

🔒 Visibility change disabled for now.

Explanation: Commented command is skipped without deletion. Use Case: Disable live commands during staging or testing.

5.5 Script Metadata Header

Input:

#!/bin/bash
# ---------------------------------------------------
# Script Name : wp_backup_daily.sh
# Author : Donny Ari
# Description : Automated backup script for WordPress
# Version : 1.2
# Date : 2025-10-09
# ---------------------------------------------------
tar -czf /home/wpbackup/wp_backup_$(date +%F).tar.gz /var/www/html

Expected Output:

(no terminal output)

Explanation: Header comments create professional documentation and version tracking. Use Case: Standard in production-grade Bash automation for team environments.

5.6 Commenting Cron Jobs

Input:

# Cron entry for daily WordPress backups
# 0 2 /home/user/scripts/wp_backup_daily.sh

Expected Output:

(none)

Explanation: Comments explain the cron job schedule without affecting execution. Use Case: For clarity in multi-job automation systems.

5.7 Using Here-Doc for Comment Blocks

Input:

<<COMMENT
These lines are treated as a block comment.
They’re ignored since no command consumes them.
COMMENT
echo "Resuming script execution..."

Expected Output:

Resuming script execution...

Explanation: <<COMMENT ... COMMENT acts as ignored text block. Use Case: Used to annotate deprecated code sections.

5.8 Debugging Comment Toggle

Input:

# Debug mode (optional)
#set -x
echo "Running migration..."

Expected Output:

Running migration...

Explanation: Debug command is commented out but easily re-enabled. Use Case: For controlled verbosity when debugging WP database migrations.

6. Best Practices

PracticeDescription
Comment why, not whatThe code itself shows “what”; comment adds reasoning.
Use consistent header formatHelps version tracking and collaboration.
Keep comments conciseAvoid clutter or redundancy.
Comment out potentially destructive codee.g., rm, wp db drop, etc.
Use : ' ... ' blocks for long explanationsEasier to re-enable later.
Maintain professionalismAvoid jokes or unrelated notes in production scripts.

7. Common Mistakes & Fixes

MistakeWrong ExampleCorrect ExampleExplanation
No space after ##Bad comment# Good commentImproves readability.
Comment placed mid-commandecho #Helloecho "#Hello"Comment must start before or after command, not within.
Comment inside quotesecho "Hello #world"# Hello world# loses meaning inside quotes.
Block comment inside loopfor i in ... : 'comment' donePlace block outside loopCan cause unexpected parsing issues.

8. Quick Lab – Comment-Rich Update Script

Script: wp_update_logger.sh

#!/bin/bash
# ---------------------------------------------
# Script Name: wp_update_logger.sh
# Author: Donny Ari
# Purpose: Update plugins and log output
# Version: 1.0
# ---------------------------------------------

echo "🚀 Starting WordPress plugin updates..."
wp plugin update --all --path=/var/www/html >> /var/log/wp_update.log 2>&1 # Log the output
echo "✅ Update completed at $(date)" >> /var/log/wp_update.log

# Uncomment next line to send email report:
# mail -s "WP Update Complete" [email protected] < /var/log/wp_update.log

Expected Output:

🚀 Starting WordPress plugin updates...
✅ Update completed at Thu Oct 9 19:45:01 UTC 2025

Explanation: This script combines metadata, inline, and commented-out lines for clarity and safe toggling.

9. Troubleshooting Matrix

IssueSymptomCauseSolution
Script breaks after commentComment inside commandPlace comment outside or after ;.
Comment not recognizedInside quotesPlace # outside string.
Block comment executesMissing colon in : '...'Correct syntax to : '...'.
Lost header infogrep filters itUse cat to view entire script, not grep -v '^#'.

10. Static vs Dynamic Framing

FramingDescriptionBehavior
StaticManual comments added by developerConsistent and descriptive documentation.
DynamicScript-generated notes/logsAutomated runtime context for debugging.

11. Cheat Sheet

TaskSyntax / Example
Single-line comment# This is a comment
Inline commentcommand # explanation
Block comment: ' multiple lines '
Disable a command# rm -rf /var/www/html
Script header# Author: ... Version: ...
Heredoc block<<COMMENT ... COMMENT
List only active linesgrep -v '^#' script.sh

12. Mini-Quiz

#QuestionAnswer
1What is the symbol used for single-line comments in Bash?#
2How can you write a multi-line comment block?Use : ' ... ' syntax.
3What happens if you put # inside quotes?It’s treated as a normal character.
4Why use headers in scripts?To store author, date, and purpose information.
5How do you disable a command temporarily?Prefix it with #.

Would you like me to continue with 📘 Module 3.1 – Variable Declaration next, using the same level of depth and the new “Syntax Formula” column standard?