In this topic, learn how to put comments in a shell script. For example, C and C++ programming languages use // and /* ... */ to assign comments. In Linux shell scripts, comments are denoted using the hash character #. The shell interpreter ignores everything from the # character until the end of that physical line.
Comments serve as developer documentation, making complex automation scripts readable, maintainable, and debuggable. In enterprise environments, well-commented shell scripts prevent production outages during team handoffs and audits.
# preceded by whitespace or at the start of a line, it treats all subsequent characters on that line as non-executable commentary.
1. Single-Line Comments
Single-line comments in Linux begin with the # sign. Any text after the # on the same line is discarded during lexical parsing:
#!/bin/bash
# =========================================================
# Script Name: script1.sh
# Purpose: Demonstrate basic single-line comments in Bash
# =========================================================
# Print welcome greeting to the standard output
echo "This is Comments Example"
# The above echo command prints "This is Comments Example" in the terminal output
Executing the script verifies that only executable commands run while comments are ignored:
$ chmod +x script1.sh
$ ./script1.sh
This is Comments Example
2. Inline Comments (Trailing Comments)
An inline comment is placed on the very same line as an executable command, positioned after the code. Crucial Syntax Rule: You must place a space before the # sign. Without whitespace, the shell treats # as a literal string argument!
#!/bin/bash
PORT=8080 # Listening port for web server daemon
TIMEOUT=30 # HTTP keepalive timeout in seconds
LOG_DIR="/var/log" # Root directory for audit logs
# CORRECT: Preceded by whitespace
echo "Server starting on port $PORT" # Notify administrator
# INCORRECT SYNTAX PITFALL:
# echo "Hello"#world -> prints: Hello#world (not a comment!)
3. Multiple Line Comments in Shell Scripting
Unlike languages such as C, Java, or PHP, the UNIX/Linux Shell does not have a dedicated multi-line comment token (such as /* ... */). However, Linux programmers have three reliable techniques to write multi-line commentary:
Prepending each line with # is universally supported across every UNIX shell (sh, bash, ksh, csh, zsh):
#!/bin/bash
# -------------------------------------------------------------
# Module: Database Backup Daemon
# Description: Dumps MySQL schemas, compresses archives with gzip,
# and synchronizes remote backups to Amazon S3.
# Author: Sysadmin Team <admin@veewom.com>
# Date: 2026-11-02
# -------------------------------------------------------------
echo "Executing automated backup routine..."
: << 'EOF')In Bash and POSIX shells, the colon : is a built-in null command that always returns exit status 0 (success) while consuming its arguments without taking action. By piping a Here-Document into :, you can create multi-line comment blocks without typing # on every line.
#!/bin/bash
echo "Active step 1: Pre-flight checks"
: << 'END_COMMENT'
===========================================================
DEBUGGING BLOCK (Temporarily Disabled Code)
The following routines are skipped during local unit tests:
service nginx reload
systemctl restart postgresql
curl -X POST https://api.veewom.com/webhook/notify
===========================================================
END_COMMENT
echo "Active step 2: Script continues execution smoothly"
'END_COMMENT' or 'EOF'). If left unquoted, the shell will still perform parameter expansion and command substitution inside the block (like `rm -rf /tmp/test` or $(dangerous_command)), causing unexpected side effects!
You can also bypass large sections of code by wrapping them in an if false; then ... fi condition. The shell parses the syntax but never executes the body:
#!/bin/bash
echo "Production mode running"
if false; then
echo "This block will NEVER execute"
echo "Useful for commenting out large blocks of experimental code"
tar -czf /backup/old.tar.gz /var/www/
fi
echo "Script completed"
4. The Shebang Exception: Why #!/bin/bash is Special
The very first line of a script often begins with #! (hash-exclamation, nicknamed shebang or hash-bang). While it starts with #, the Linux operating system kernel handles this line uniquely:
| Feature | Line 1 Position (#!/bin/bash) |
Line 2+ Position (Inside Code Body) |
|---|---|---|
| Handled By | Linux Kernel (execve() system call) |
Shell Interpreter Parser |
| Magic Bytes | 0x23 0x21 (Hex signature for script execution) |
Treated as standard ASCII comment string |
| Function | Instructs OS which binary loader to spawn | Ignored completely by the interpreter |
5. Enterprise Shell Script Header Standard
In professional software engineering, every production shell script should start with a comprehensive documentation header block:
#!/bin/bash
###############################################################################
# Script Name : system_health_check.sh
# Description : Monitors CPU load, RAM usage, and root partition disk space.
# Author : Veewom Engineering Team
# Email : support@veewom.com
# Version : 2.4.0
# Created Date : 2026-11-02
# License : GNU GPLv3
#
# Arguments :
# $1 - Alert email address (e.g. admin@veewom.com)
#
# Exit Codes :
# 0 - Normal (all health thresholds passed)
# 1 - Missing required command-line argument
# 2 - Disk partition exceeds 90% threshold
###############################################################################
6. Summary Comparison of Comment Methods
| Comment Technique | Syntax | Portability | Best Use Case |
|---|---|---|---|
| Single-Line Hash | # Comment text |
100% (All Shells) | Short notes, variable explanations, step labels |
| Inline Comment | CMD # Note |
100% (All Shells) | Brief variable annotations and parameter flags |
| Multi-Line Hash | Multiple # lines |
100% (All Shells) | Script headers, function docs, algorithms |
| Quoted Heredoc | : << 'EOF' ... EOF |
Bash, Korn, POSIX | Temporarily disabling large code blocks during debugging |
| False Condition | if false; then ... fi |
100% (All Shells) | Testing alternate execution branches |
7. Hands-on Lab Practice Drill
Create a script named comment_demo.sh that uses single-line comments, inline comments, script headers, and function documentation:
$ cat << 'EOF' > comment_demo.sh
#!/bin/bash
# -------------------------------------------------------------
# File: comment_demo.sh
# Purpose: Demonstrate professional commenting standards
# -------------------------------------------------------------
# Define global configuration constants
THRESHOLD=85 # Disk usage alarm percentage
LOGFILE="/tmp/disk_audit.log" # Output audit report path
# -------------------------------------------------------------
# Function: calculate_usage
# Description: Checks current usage percentage of the root filesystem
# Arguments: None
# Returns: Integer (0-100)
# -------------------------------------------------------------
calculate_usage() {
# Extract current percentage using df and awk
local current_usage
current_usage=$(df / | awk 'NR==2 {gsub("%",""); print $5}')
echo "$current_usage"
}
# --- Main Program Execution ---
usage_pct=$(calculate_usage)
echo "Current Root Usage: ${usage_pct}%" >> "$LOGFILE"
if [ "$usage_pct" -gt "$THRESHOLD" ]; then
# WARNING: Disk capacity critically high
echo "[CRITICAL] Disk space usage is ${usage_pct}%!"
else
# Status is within safe operational limits
echo "[OK] Disk space healthy at ${usage_pct}%."
fi
EOF
$ chmod +x comment_demo.sh
$ ./comment_demo.sh
[OK] Disk space healthy at 42%.
8. University Viva & Job Interview Q&A
Answer: Inside $(...) (modern command substitution), a # is recognized as a comment until the closing newline. Inside legacy backticks `...`, however, escaping rules differ and placing # can cause parsing errors or unclosed backtick warnings. Always use $(...) in modern scripts.
Answer: Wrap the # inside single or double quotes, or escape it with a backslash: echo "#1 Veewom Linux" or echo \#1 Rank. Unquoted # preceded by whitespace will be stripped away as a comment.
Answer: Negligibly. The shell parser skips comment lines during lexing in microseconds. The readability and security benefits of clear documentation overwhelmingly outweigh sub-millisecond parsing overhead.
9. Frequently Asked Questions (FAQ)
No. Linux shell scripting has no official multi-line block delimiter. The standard POSIX approach is using # at the start of each line, or the null command : << 'EOF' ... EOF heredoc trick.
echo "text"#comment print the comment?Because the shell requires whitespace (a space or tab) before the # character to distinguish a comment token from a word. Without whitespace, #comment is treated as an attached string.
Learn system variables, user definitions, export, and scoping in Class 16: Variables in Shell Scripting.
Continue to Class 16: Variables in Shell Scripting → Previous: ← Shell Keywords | Full Syllabus