Writing Comments in Bash
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 # ba single piece of text, so the#is printed. - In the third line,
a#bis one word, and the#is not at its start. - In the fourth line,
#bis a new word that starts with#, so it and the rest of the line are ignored. Onlyais 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.