Bash by Example: Comments
Learn how to write single-line and multi-line comments in Bash to document your code with this sample code.
Code
#!/bin/bash
# This is a single-line comment
# Bash ignores everything after the #
echo "This will run" # Inline comment
: '
This is a "hack" for multi-line comments.
Since the colon (:) is a null command that does nothing,
and single quotes define a string,
this block is effectively ignored.
'
echo "Script finished"Explanation
Bash primarily supports single-line comments using the hash symbol #. Any text following a # on a line is treated as a comment and ignored by the shell. This is used for explaining code logic, disabling lines temporarily, or adding metadata.
Unlike languages like C or Java, Bash does not have a native syntax for multi-line block comments (like /* ... */). However, developers often use a workaround using the null command : combined with a Here Document or a quoted string. The most common "hack" is : '...', which creates a string that is evaluated but done nothing with.
Good commenting practice is essential in Bash scripting because shell syntax can be terse and obscure. Explaining why a complex regex or parameter expansion is used is often more valuable than explaining what it does.
Code Breakdown
# starts a standard single-line comment. These lines are completely skipped during execution, serving purely as documentation.echo "..." # ... demonstrates an inline comment. The command executes, but the text following the hash is ignored.: ' begins a multi-line comment hack. The colon is a null command that does nothing, and the single quote starts a string.' closes the multi-line string. Since the colon command does nothing with its arguments, this block effectively acts as a comment.
