[#when-to-use-bash-comments]When to use Bash comments[#when-to-use-bash-comments]
Just like comments are used in other programming languages, you can also use them throughout your shell scripts to make them more readable. For example, if you’ve written a script for others to use, comments help explain the purpose of certain lines. They can also help you, the developer, quickly remember your thought process from when you wrote the script.
Comments should be used to complement clean, organized Bash scripts. They should only be used to explain less obvious parts of the code. For example, most developers reading an echo statement will know how it works, but a user-defined function may be harder to immediately understand, so a shell script comment would be helpful there.
To create a single-line comment in a Bash script, begin the comment with a hash (#) symbol. Bash ignores everything after the hash, so even if you include code snippets in comments, they won’t be executed.
A comment can be on a line alone:
A comment can also be on the same line as script code:
Unfortunately, there is no built-in way to write multi-line comments in Bash. But here are some workarounds.
[#multiple-single-line-comments]Multiple single-line comments[#multiple-single-line-comments]
You can use multiple single-line comments to make up a larger overall comment:
[#colon-and-single-quotes]Using a colon and single quotes[#colon-and-single-quotes]
The simplest workaround is using the colon and single quote characters:
You can also assign an arbitrarily named variable to a multi-line string to serve the same purpose as a comment - it’s still a block of text that’s recognizable to anyone using your shell script. This is useful if you want to give the comment a name.
You can utilize the HereDoc redirection mechanism as a workaround to write multi-line comments in Bash. Usually, HereDoc is used when you need to pass more than one input line to a command, but if you don’t specify a command, the lines have no effect and can serve as a way to write “comments” spanning multiple lines.
Keep in mind that commenting through HereDoc is not officially supported by Bash, so it’s best practice to stick to hash symbol comments, or the above.
Read more about commenting in bash in the official bash man pages.