What Are Bash Comments?
In Bash scripting, comments are notes in your code that the computer skips. They help you and others understand what your script does without affecting how it works. In Bash, comments begin with the #
sign and run until the end of the line.
Example:
# This line is a comment and won't be run by Bash
echo "Hello, World!" # This part after # is also a comment
1. Single-Line Comments
- Just start a line with
#
. - This is the easiest and most reliable way to make comments.
- Good for explaining individual lines or sections of code.
Example:
# Set variable
greeting="Hello"
echo "$greeting, user!"
2. Inline Comments
- You can add a comment after code on the same line using
#
. - Keep these short to avoid clutter.
Example:
echo "Done processing" # Let the user know the script finished
Note: Some developers advise using inline comments sparingly for better readability.
3. Multiline or Block Comments
Bash doesn’t officially support block comments like /* ... */
in other languages. But there are two common workarounds:
a) Hash (#
) per Line
This is simple and always works:
# Initialize values
# Check user input
# Process the result
This method is the safest and clearest option.
b) Here-Document with :
(Null Command)
This uses a Bash trick to ignore a whole block, though it’s more advanced and less obvious to people reading your script:
: << 'COMMENT'
This is a multiline comment.
Everything here is ignored by Bash.
COMMENT
The :
is a command that does nothing (“null command”), and the text between the << 'COMMENT'
and the matching COMMENT
is treated as input but ignored.
On UNIX StackExchange, a user warns that this method can do unintended things like variable substitution or extra CPU usage so it’s better to stick with #
lines for clarity and safety.
4. The Special Case: Shebang (#!
)
The first line of many Bash scripts starts with something like:
#!/bin/bash
This is called the shebang and tells the operating system which interpreter to use. While it looks like a comment, it’s actually a special instruction and not ignored.
Final Thoughts
- Use
#
for nearly all commenting. - Be clear, helpful, and consistent.
- Reserve the HereDoc trick for quick, temporary block commenting but keep it rare.
- Always include a well-formed shebang if your script is executable.