Writing Comments in Bash

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 29 of 205

A comment is text in a script that Bash ignores. Its purpose is to explain the script to the people who read it, including you in six months' time. A single character starts a comment in Bash, the hash sign #, but the exact rules about where that character counts are subtle, and they affect quoting, special variables and multi-line comments. This lesson covers all of them.

Understanding the Concept

When Bash reads a script, it divides each line into words, separated by spaces. If a word begins with #, Bash treats that word and everything up to the end of the line as a comment and throws it away. A comment never changes what the script does; it exists only for the reader.

There is no comment syntax that has a closing marker. A comment always ends at the end of the line, so a longer explanation is written as several lines that each begin with #.

Single-Line Comments

A line that begins with # is a comment line:

#!/usr/bin/env bash
# c1.sh - demonstrate comments.

# A comment on its own line.
echo "Step 1"   # a comment after a command

Output of the commands:

Step 1

Two kinds of comment appear here. The line starting with # is wholly a comment. The text after echo "Step 1" is an inline comment: Bash runs the command and ignores the remainder of the line. Put at least one space before the # of an inline comment, so that it starts a new word.

Blank lines are also ignored, and they are useful for separating the parts of a script.

The Shebang Is Also a Comment

The first line #!/usr/bin/env bash begins with #, so Bash treats it as a comment. It has meaning only to the operating system, which reads it before Bash starts. That is why the same file can be run with bash script.sh and still work.

When a # Does Not Start a Comment

A # starts a comment only at the beginning of a word. It is plain text when it is part of a word or inside quotes. This is shown by the following lines in a script:

echo "a # b"        # hash inside double quotes is text
echo 'a # b'        # hash inside single quotes is text
echo a#b            # hash in the middle of a word is text
echo a #b           # hash that starts a word begins a comment

Output:

a # b
a # b
a#b
a
  • In the first two lines, the quotes make a # b a single piece of text, so the # is printed.
  • In the third line, a#b is one word, and the # is not at its start.
  • In the fourth line, #b is a new word that starts with #, so it and the rest of the line are ignored. Only a is printed.

The hash also has other jobs in Bash that are not comments:

name="Suriya"
echo "${#name}"     # ${#name} is the length of the variable, not a comment
set -- x y z
echo "$#"           # $# is the number of arguments, not a comment

Output:

6
3

${#name} gives the number of characters in the variable name, and $# is the count of positional parameters. In both, the # is attached to other characters, so it does not begin a word. The set -- x y z command, explained in a later lesson, simply assigns three arguments so that $# has something to count.

Commenting Out Code

A common use of comments is to disable a line without deleting it. This is handy while testing:

# echo "This line is commented out"
echo "Step 2"
Step 2

Only the second echo ran. Remove the # to bring the first one back. Because deleted code is easy to forget, remove commented-out code that you no longer need.

A Header Comment

A short comment at the top of a script, after the shebang, tells readers what the script is, who it is for and how to use it:

#!/usr/bin/env bash
# backup_notes.sh - copy the notes folder to a dated backup.
# Usage: ./backup_notes.sh [source-folder]
# Exit status: 0 on success, non-zero if the copy fails.

Such a header costs a few lines and saves a reader from opening the whole file. Keep it accurate: when the script changes, update the header.

Multi-Line Comments

Bash has no /* ... */ block comment. You have two choices.

Option 1: several lines that each begin with #. This is the normal, clearest choice:

# This function retries the download up to three times.
# It waits two seconds between attempts, because the server
# limits how often a client may connect.

Option 2: a here document with the null command. The : command is a built-in that does nothing and always succeeds. A here document (a block of text fed to a command, explained in a later lesson) gives it a long text to ignore:

#!/usr/bin/env bash
: <<'NOTES'
This block is never executed.
It can span many lines and may contain
anything, such as $(date) or "quotes".
NOTES
echo "script continues"

Output:

script continues

Quoting the delimiter, as in <<'NOTES' with single quotes, is essential. With a quoted delimiter, Bash does no expansion inside the block. Without quotes, the text is expanded, and any command substitution in it really runs. This test uses a harmless substitution that writes a message to standard error:

: <<NOTES
Result: $(echo expansion-ran >&2)
NOTES
echo "done"

Output:

expansion-ran
done

The "comment" executed a command. For this reason, and because editors and other readers do not recognize the trick as a comment, most scripts use ordinary # lines even for long explanations. The here document form is useful mainly for temporarily disabling a large block of code.

Another way to disable a block is to place it inside if false; then ... fi:

if false; then
echo "disabled code"
fi
echo ok
ok

This keeps the code checked for syntax errors, which a real comment does not.

Comments Inside Longer Commands

A comment may appear after a pipe or && at the end of a line, because Bash expects more input after those operators:

sort letters.txt |   # sort the lines
  head -n 2          # keep the first two

With letters.txt holding the lines b, a and c, the output is:

a
b

Comments also work inside the parentheses of an array assignment, one for each element:

files=(
  a.txt   # first
  b.txt   # second
)
echo "${#files[@]} items: ${files[*]}"
2 items: a.txt b.txt

(The expression ${#files[@]} counts the elements of an array. Arrays are covered in a later lesson.)

Comments and Line Continuation

A backslash at the end of a line joins it to the next line. Two cases show how this interacts with comments.

A comment line that ends with a backslash is still a comment, and the backslash does not continue it onto the next line:

# this comment ends with a backslash \
echo "still runs"
still runs

You also cannot put a comment after a continuation backslash on the same line. A backslash followed by a space escapes the space, and the # then sits in the middle of a word instead of starting one:

echo hi \ # comment

Output:

hi  # comment

The comment was printed, because it was not a comment at all. Put the comment on its own line before the command, or after the whole command.

Comments Cannot Stand Alone in a Body

A function, an if or a loop needs at least one real command in its body. A body made of comments alone is a syntax error:

todo() {
  # only a comment
}

Output:

c11.sh: line 3: syntax error near unexpected token `}'
c11.sh: line 3: `}'

The fix is to use the : command as a placeholder, because it is a command that does nothing:

todo() {
  # not implemented yet
  :
}
todo
echo "status=$?"
status=0

The same applies to an empty then branch of an if.

Comments in an Interactive Shell

At the terminal, # also starts a comment, because the interactive_comments option is on by default:

shopt interactive_comments
interactive_comments	on

This is useful when you paste commands that contain explanations. In some other shells, for example Zsh, the option has to be enabled first, so a pasted # there may be treated as an argument.

Special Comments

Some comments carry instructions for tools, and Bash itself ignores them. The shebang is one. Another is a directive for the ShellCheck analyzer, covered in a later lesson, which tells it to skip a certain warning for the next line:

# shellcheck disable=SC2034
unused_variable="kept for later"

Bash sees only a comment.

Choosing What to Comment

Comments are most useful when they say something the code does not. Compare:

# bad: repeats the code
count=$((count + 1))   # add one to count

# useful: explains the reason
retries=$((retries + 1))   # the server rejects the first call after login

The first comment restates what any reader can see. The second records a reason that would otherwise be lost. A comment can also warn about a surprise, name the source of a formula or a command option, or mark the unfinished parts of a script. Short comments that stay accurate are more valuable than long ones that fall out of date.

Practical Applications

Reading a configuration file that uses comments. Many configuration files use # for comments, and a script often needs to skip them. This command drops comment lines and blank lines:

printf '# header\nkeep this  # trailing\n\nkeep that\n' > cfg.txt
grep -v '^[[:space:]]*#' cfg.txt | grep -v '^$'
keep this  # trailing
keep that

The first grep -v removes lines whose first non-space character is #, and the second removes empty lines. The trailing comment on the first kept line stays, because the pattern only matches comments at the start of a line.

Checking a script without running it. The -n option makes Bash read the script and report syntax errors without running any command:

bash -n c1.sh && echo "syntax ok"
syntax ok

This is a quick check after you add or remove comment markers around a block of code.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Writing Comments in Bash and get answers drawn from it.

Signed-in readers only.