Site icon DesignLinux

Writing Comments in Bash Scripts

Writing Comments in Bash Scripts

It’s a best practice to make bash script in a clean and understandable way. You can make you code clean and arrange by indenting, blocks and giving related names of variables and functions. You can also improve the code readability using comments. Comments are human-readable explanation or short description. In this article we will show you how to write comments in bash script.

Giving comment on your bash script will be easy to understand in future and save the time. For example, if you wrote a bash script years ago and want to make changes then it will be easy if you given section wise comments in script. Otherwise it will take time to study the all code and then make changes.

It will also help if the new developers or system administrators who is currently working on the script can understand your code fast and properly.

Generally, comments are description of code, like if you have make custom regex or complex logic in your bash script. Comments will explain why you wrote such code and what it does. Remember that comments should short and meaningful.

Writing Comments in Bash

In bash, the has # symbol is used to ignore the characters after it. You can use the # to give the comment. It can be added at the beginning on the line or inline with other code:

# Bash comment example.
echo "Test bash code" # Inline Bash comment.

Generally, comments are represented in green color if your text editor supporting syntax highlighting.

At the time of testing bash script the comment is useful to ignore some of code lines or blocks.

# if [[ $i -gt 5 ]]; then
#  echo "value is greater."
# fi

Multiline Comments in Bash

Bash doesn’t support multiline comments like other programming languages. The easiest way to write multiline comments in Bash is to add single comments one after another:

# first line.
# second line.

You can use the HereDoc as an alternate way. It allows you to pass multiline of input to a command.

<< 'MULTILINE-COMMENT'
    The body of 
	HereDoc is considered
	as comments
MULTILINE-COMMENT

It is recommended that use the single line comments to avoid any issues.

Conclusion

It is always best practice to add comments while writing bash script. Which will help understand in future and also help to other developers to understand codes. In Bash, everything after the hash mark (#) and until the end of the line is considered to be a comment.

If you have any question or feedback, please leave a comment below.

Exit mobile version