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.
Key Takeaways
- Learning about what are the Bash comments.
- Learning the usage of Bash comments.
- Comparing the types of Bash comments.
What Are Bash Comments?
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.
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 usual to write a Bash script, leave it and not check it for a couple of months. Now, 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:
Steps to Follow >
➊ Open your Ubuntu Terminal.
➋ Create a file with an extension of ‘file.sh’ in the following manner:
touch file.sh
- touch: Creates files.
- file.sh: The file I have created. You can name it any of your choices.
➌ Now, to open the script in the nano text editor, write the command below:
nano file.sh
- nano: A text editor.
- file.sh: The script I have created.
➍ Then, append the line including ‘Shebang’ in the script:
#!/bin/bash
Here, #!: Shebang or Hashbang operator. And /bin/bash dictates the path to the Bash interpreter.
➍ Afterward, write programs in the script and adorn your script by using any kind of commenting style within the codes according to the requirement:
Script (file.sh) >
#!/bin/bash
#This script is for printing information
#Printing a user’s name
echo “Nadiba Rahman”
#Printing a website’s name
echo “linuxsimply.com”
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.
➎ Finally, all you need to do is to click 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 which 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: In the Bash script, there is no built-in method to write multi-line comments.
Comparative Analysis of the Two Bash Comments
A little comparative analysis chart between single-line & multiple-line comments in Bash is here:
Types | Pros | Cons |
---|---|---|
Single Line Comments |
|
|
Multiple Line Comments |
|
|
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. Only then, it’ll make sense of doing so.
Script (purpose.sh) >
#!/bin/bash
#Script name: purpose.sh
#Purpose:
#Codes here
Here, in ‘#Purpose:’, you will write the purpose and target of your script.
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.
Script (functions.sh) >
#!/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
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.
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.
Script (variable.sh) >
#!/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.”
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.
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:
Script (tags.sh) >
#!/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:
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.
The above image displays the convention comments in a script.
E. Documentation Tools
Using some tools like ‘BashDoc’, ‘Doxygen’, and ‘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
Related Articles
- The Art of Commenting in Bash
- Bash the Hash! – a Symbolic Feature of Bash Comment
- What Are Single-line Comments in Bash? [2 Cases With Examples]
- Multiple Line Comments in Bash [2 Cases With Examples]
- How to Use Block Comment in Bash? [2 Cases]
<< Go Back to Bash Scripting Tutorial