How to Add Comments in Bash Scripts

  1. Single Line Comments in Bash
  2. Multi-Line Comments in Bash

Comments are the lines that the interpreter ignores and are just used to describe what’s happening in the code or give insight about what particular block or line of code is doing. Comments make the code easier to understand for the ones who reads the code. We can describe what’s happening in code in human language using comments. It can also be helpful when we review our code after some time of writing the code. Comments are also useful while debugging the code. Instead of removing the part suspected of having a bug, we can comment out the particular part and debug the code.

We can write comments in Bash using # and heredoc. Generally, # is used to write single-line comments, and heredoc is used to write multi-line comments.

Single Line Comments in Bash

We use # symbols to write single line commands in Bash. After #, everything is ignored while interpreting the script except the first line which contains #!. This specific sequence #! that appears on the first line is called Shebang, and it is used to decide which interpreter to use.

Comments can begin from the beginning of the line, or they can even be inline with code.

#!/bin/bash
echo "Hello World!" # echo is similar to print statement.
# end of the code 

Output:

Hello World!

Here, the first line suggests the compiler to be used is /bin/bash.

In the second line, we have the inline comment and in the third line, we have a comment beginning from the start of the line.

Multi-Line Comments in Bash

Bash does not have support for multi-line comments. One way to write multi-line comments in Bash is by using a single line comment for each line.

# This is a 
# multiline comment in Bash
echo "Hello World!"

Output:

Hello World!

Here, lines 1 and 2 can be considered as multi-line comments where each line is interpreted as a separate comment by the interpreter.

We can also take advantage of Heredoc to write multi-line commands. Heredoc is a method to pass multi-line inputs to a command. We can use Heredoc as a multi-line comment if the Heredoc is not redirected to any command.

#!/bin/bash

<< 'Comment'
    Everything inside the
    HereDoc body is
    a multiline comment
Comment
echo "Hello World!" 

Output:

Hello World!

Here, the lines 3-7 is considered as a multi-line comment by the interpreter.

comments powered by Disqus