Bash Comments

One of the most important factors to consider while writing a Bash script is comments. Comments add explanatory logic to the script to make the program more appealing and understandable to readers. Commenting throughout a script is a good practice you should be keeping as it answers all the questions of the unknown terms to readers when you are no longer around or you want to revise a screenplay you wrote a long time ago. In this article, you will get introductory ideas about the basics of Bash comments.

What Are Bash Comments?

In Bash, comments are strings or pieces of text added to the code of a Bash script that provide an informative note or concise description of the program. Generally in Bash, you can identify comments appending the hash (#) symbol. A line starting with the # symbol is only for reference and ignored by the Bash interpreter while executing the commands in the script.

Only Exceptional Case: Shebang (#!), written at the start of the script & prefixed with a hash (#) symbol, is not a comment; instead, it instructs the operating system on which interpreter to employ.

Comments in Bash script

The above image is a little glimpse of a Bash comment where you can see shebang(#!) in the first line of the script. Here, in the script bash-comment.sh, the line written with a hash symbol refers to the Bash comment.

When to Use Bash Comments?

It’s common to write a Bash script, set it aside, and not revisit it for several months. When you eventually return to it, you will need to acquaint yourself with the whole code again. Comments clarify the process and help you to keep the scripting track here.

Again, suppose, you have written a script for other users. Comments, in this case, will simplify the less obvious parts of the program and make the whole script organized to them. Anyone by exploring the whole script written with comments can easily understand and interpret your thoughts.

How to Comment in Bash?

Bash hashing is a very important factor while commenting in a Bash script. So, if you want to write comments in a Bash script, then follow the step-by-step process mentioned below:

  1. Open your Ubuntu Terminal.

  2. Create a file with an extension of file.sh in the following manner:

    touch file.sh

    EXPLANATION
    • touch: Creates files.
    • file.sh: The file I have created. You can name it any of your choices.

    Creating a new file using 'touch' command

  3. Now, to open the script in the nano text editor, write the command below:

    nano file.sh

    EXPLANATION
    • nano: A text editor.
    • file.sh: The script I have created.

    Opening file in Nano text editor

  4. Then, append the line including Shebang in the script:

    #!/bin/bash

    EXPLANATION

    Here, #!: Shebang or Hashbang operator. And /bin/bash dictates the path to the Bash interpreter.

    The line starting with 'Shebang' in Bash script

  5. Afterward, write programs in the script and adorn your script by using any kind of commenting style within the codes according to the requirement:

    #!/bin/bash
    
    #This script is for printing information
    
    #Printing a user’s name
    echo “Nadiba Rahman”
    
    #Printing a website’s name
    echo “linuxsimply.com”

    EXPLANATION

    Here, “#This script is for printing information” tells the purpose of the whole script. Then, “#Printing a user’s name”, and “#Printing a website’s name” explains the step-by-step code.

    Comments within codes in a Bash script

  6. Finally, all you need to do is type CTRL+S to save the file and then click CTRL+X to exit.

Why Are Bash Comments So Important?

Compressed and to-the-point documentation within the programs is the main target of using comments in a Bash script. These are helpful as the internal annotations let you understand the output that is likely to appear or what the next command will execute. The Bash comments generally aid in:

  • Magnifying the context.
  • Improving Program Readability.
  • Intensifying Code Maintenance.
  • Strengthening Collaboration.
  • Facilitating the Troubleshooting.

Types of Comments in Bash

There are two types of comments in Bash script: Single-line comments & multiple-line comments. A little viewpoint regarding this:

  • Single Line Comments in Bash: A single-line comment starts with a ‘#’ symbol.
  • Multiple Line Comments in Bash: There is no built-in method to write multi-line comments in the Bash script.

To know more about the Bash comments, visit – Single-line commentsMultiple-line comments, and Block comments.

Comparative Analysis of Two Types of Comments in Bash

A little comparative analysis chart between single-line & multiple-line comments in Bash is here:

Types Pros Cons
Single Line Comments
  • Short & concise.
  • Supports nested scheme.
  • Quick.
  • Limited length.
  • Visually messy when numerous in number.
Multiple Line Comments
  • Clear & extensive.
  • High readability.
  • Doesn’t support the nested scheme.
  • No built-in support.

Which type of comment needs to prefer, depends on the requirement of the detailing level of users and the organizations. For a fast-forward explanation, you may choose a single-line commenting style. Otherwise, for detailed and comprehensive documentation, you may approach multiple-line commenting. As you have already got the pros and cons of both styles, now you can strike a good balance of comments.

In-depth Exploration of Bash Commenting

Master the Art of Commenting by deeply exploring several commenting aspects in Bash like the following section:

A. Explaining Script Purpose

Suppose, you have started coding right after opening a Bash script. Except for you, no one will understand the code at first glance. After a few days, even you won’t get the reason for what you wanted to do that code. So, for self and others’ betterment, it’s a must thing to comment out the purpose of what you are going to do at the beginning of any script shortly. Check the following script for the practical approach:

#!/bin/bash

#Script name: purpose.sh
#Purpose:
#Codes here
EXPLANATION

Here, in “#Purpose:”, you will write the purpose and target of your script.

Writing purpose as comments

From the above image, you can see the marked portion where you must write the purpose of your script to make it more engaging.

B. Commenting Functions

A function within a code contains some components like input parameters, arguments, return values, etc. Function comments play an indispensable role in this case. Comments disclose the purpose of every component & clear each level inside a function. See the below script as an example:

#!/bin/bash

#Function: new_user
#Purpose: This function greets new users
#Parameters:
# $1: Name of the first user
#Returns: No return values

new_user() {
name =$1
#Print the welcome message
echo “Hello, $name! Welcome.”
}
#Greet the user X
new_user X
EXPLANATION

Here, “#Function: new_user” tells what the function name is. And “#Purpose: This function greets new users” indicates the target of the script. Then, “#Parameters:” and “# $1: Name of the first user” dictates the parameters used in the code. After that, “#Returns: No return values” shows the return values if the function has any. Now, “#Print the welcome message” displays to print the message inside the echo command. Finally, “#Greet the user X” tells us to add user X as the new user.

Writing comments inside functions

In the above snapshot, you can see the function comments written in the highlighted areas.

C. Commenting Variables

Variables with enigmatic names inside the Bash script are quite confounding for the readers. Comments expound on the usage of those variables to make the script more appealing to the users. Go through the below script to check the process:

#!/bin/bash

#Purpose: This script calculates the area of a rectangle.

#Variables
#length: This stores the length of the rectangle in units.
#width: This stores the width of the rectangle in units.

length=3 #Rectangle’s length
width=2 #Rectangle’s width

#Calculate the area by multiplying the length & the width
area=$((length * width))

#Display the result
echo “The area is: $area square units.”
EXPLANATION

Here, “#Purpose: This script calculates the area of a rectangle.” indicates the goal of the script. In the “#Variables” section, “#length: This stores the length of the rectangle in units.”, and “#width: This stores the width of the rectangle in units.” represent the variables used in the script and what they mean here. Then, “#Rectangle’s length”, and “#Rectangle’s width” define inserted values to the variables. Afterward, ‘#Calculate the area by multiplying the length & the width” declares to calculate the desired task by using the variables. And finally, “#Display the result” shows the calculated result.

Writing variable comments

The above screenshot shows the usage of variable comments in a script.

D. Commenting Tags or Conventions

Tags or conventions are particular notations or labels that are used to provide extra information and instructions to improvise the commenting structure. Some commenting tags in Bash are:

#!/bin/bash

#Constants
Readonly max_retries=3  #Maximum number of retries for a failed case
Readonly log_file="script.log"  #The log file path

#NOTE: This for loop may hamper performance
for i in {1..50}; do
#codes here
done

#TODO: Append error handling for edge cases

#FIXME: Find issues with file permissions
#Observe behavior:

#HACK: Though this method works, it's not the efficient one.
#suggestions:
EXPLANATION

Here, “#NOTE: This for loop may hamper performance”, “#TODO: Append error handling for edge cases”, “#FIXME: Find issues with file permissions”, and “#HACK: Though this method works, it’s not the efficient one.” are the convention comments which add some additional information to the script.

Adding tags or conventions as comments

The above image displays the convention comments in a script.

E. Documentation Tools

Using some tools like BashDocDoxygen, Mardkwon, etc., you can generate documentation from the comments in your Bash script. But while using these tools it’s very important to follow some specific commenting patterns which are applicable to the tool you are using.

Tips for Checking & Updating Bash Comments

Outdated comments can mislead and create algorithmic errors. So, it’s very important to check regularly if the comments are updated or not.  Follow the tips below to review & update Bash comments properly:

  • Review the Bash comments regularly to make sure that they state the current condition of the code.
  • Remove the inaccurate comments and update them by changing the variables, functions, algorithms, etc. as per requirement.
  • Use the same phrasing format throughout the comments to keep consistency.
  • Simply avoid the fusion of complex languages. Only use plain and manageable terms while commenting.
  • Use version control to review the changes over time and track the state of Bash comments to spot potential errors.

Conclusion

By now, you have got that the Bash comments are nothing but an important interpretation of Bash codes. So, use more comments as logically as possible to keep track of your script.

People Also Ask

What is the basic syntax for Bash comments?

The basic syntax for writing a Bash comment is a hash (#) symbol before a line. Everything following the # symbol on the same line is considered a comment and is ignored by the Bash interpreter.

Are comments visible while listing up a directory’s contents?

No, comments are not visible during a directory’s contents listing execution.

Can I add metadata in Bash script using comments?

Yes, you can add metadata by commenting in the Bash script. This can include details such as the script’s purpose, author, creation date, and any other relevant information.

Is it mandatory to use comments in Bash?

No, it’s not mandatory to use comments in Bash. Actually, it’s just for the clarification of the script.

Can I remove comments once I insert them in Bash?

Yes, you can remove comments from Bash whenever you want. But you have to do it manually.

Can I use both single-line & multiple-line comments in a Bash script?

Of course! You can use both. Actually, it’s up to you how you will organize your script.

Do comments affect a running program?

No, comments are text used to explain the code logic. They don’t have any impact on the performance of your running program.

Related Articles


<< Go Back to Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment