Comment in linux bash

Way to create multiline comments in Bash?

I have recently started studying shell script and I’d like to be able to comment out a set of lines in a shell script. I mean like it is in case of C/Java :

/* comment1 comment2 comment3 */` 

It should be noted that the below answers require that the : be in the first column (no leading spaces) in the line.

12 Answers 12

Use : ‘ to open and ‘ to close.

: ' This is a very neat comment in bash ' 

🙁 and also adds a great amount of un-read-ability and potential bug-source. IMHO is better just use multiple # s and never this.

to explain: : is shorthand for true and true does not process any parameters. (manual page: SYNOPSIS true [ignored command line arguments]

I modified this slightly for blocks of code so I can easily switch the code either on or off. My change is to use # ‘ on the last line instead of the single quote. This way I can put a single # on the first line to activate the block of code. Remove the # on first line to deactivate the code.

Multiline comment in bash

It’s probably worth noting that this is not a comment per se. This is a heredoc that is redirected to NOP command as a multi-line string. Single quote is important to disable resolving variables and commands.

I tested this in a simple bash script that runs via it’s shebang line, #!/bin/bash in Debian and it failed. I’m trying each answer on this page, and they’ve all failed until I got to the one below. Since they failed, I am down-voting them, and up-voting the one that actually runs properly.

Note: I updated this answer based on comments and other answers, so comments prior to May 22nd 2020 may no longer apply. Also I noticed today that some IDE’s like VS Code and PyCharm do not recognize a HEREDOC marker that contains spaces, whereas bash has no problem with it, so I’m updating this answer again.

Bash does not provide a builtin syntax for multi-line comment but there are hacks using existing bash syntax that «happen to work now».

Personally I think the simplest (ie least noisy, least weird, easiest to type, most explicit) is to use a quoted HEREDOC, but make it obvious what you are doing, and use the same HEREDOC marker everywhere:

Single-quoting the HEREDOC marker avoids some shell parsing side-effects, such as weird subsitutions that would cause crash or output, and even parsing of the marker itself. So the single-quotes give you more freedom on the open-close comment marker.

For example the following uses a triple hash which kind of suggests multi-line comment in bash. This would crash the script if the single quotes were absent. Even if you remove ### , the FOO<> would crash the script (or cause bad substitution to be printed if no set -e ) if it weren’t for the single quotes:

set -e > something more comment ###BLOCK-COMMENT ls 

You could of course just use

set -e > something more comment ### ls 

but the intent of this is definitely less clear to a reader unfamiliar with this trickery.

Читайте также:  При загрузке linux пишет grub

Note my original answer used ‘### BLOCK COMMENT’ , which is fine if you use vanilla vi/vim but today I noticed that PyCharm and VS Code don’t recognize the closing marker if it has spaces.

Nowadays any good editor allows you to press ctrl-/ or similar, to un/comment the selection. Everyone definitely understands this:

# something something $> something # more comment # yet another line of comment 

although admittedly, this is not nearly as convenient as the block comment above if you want to re-fill your paragraphs.

There are surely other techniques, but there doesn’t seem to be a «conventional» way to do it. It would be nice if ###> and ###< could be added to bash to indicate start and end of comment block, seems like it could be pretty straightforward.

Источник

Написание комментариев в сценариях Bash

При написании сценариев Bash всегда рекомендуется делать код чистым и понятным. Организация кода в блоки, создание отступов, присвоение описательных имен переменных и функциям — вот несколько способов сделать это.

Еще один способ улучшить читаемость вашего кода — использовать комментарии. Комментарий — это понятное для человека объяснение или аннотация, написанная в сценарии оболочки.

Добавление комментариев к вашим сценариям Bash сэкономит вам много времени и усилий, если вы посмотрите на свой код в будущем. Допустим, вы хотите изменить сценарий, написанный несколько месяцев или лет назад. Скорее всего, вы не вспомните, почему вы написали какой-то сложный фрагмент кода, если не добавили комментарий.

Комментарии также помогают другим разработчикам и системным администраторам, которым может потребоваться поддержка скрипта, чтобы понять ваш код и его назначение.

Комментарии используются для объяснения кода. Например, если у вас есть сложное регулярное выражение или подстановка параметров внутри вашего сценария Bash, вы должны написать комментарий, описывающий, что делает код. Комментарии должны быть краткими и по существу. Не объясняйте что-то простое и очевидное для читателя.

В этой статье мы рассмотрим основы написания комментариев в Bash.

Написание комментариев в Bash

Bash игнорирует все, что написано в строке после решетки ( # ). Единственное исключение из этого правила — первая строка скрипта начинается с символа #! символы. Эта последовательность символов называется Shebang и используется для указания операционной системе, какой интерпретатор использовать для анализа остальной части файла.

Комментарии могут быть добавлены в начале строки или встроены в другой код:

# This is a Bash comment. echo "This is Code" # This is an inline Bash comment. 

Пробел после решетки не является обязательным, но он улучшит читаемость комментария.

Если ваш текстовый редактор поддерживает выделение синтаксиса, комментарии обычно отображаются зеленым цветом.

Комментарии также полезны при тестировании скрипта. Вместо удаления некоторых строк или блоков вы можете закомментировать их:

# if [[ $VAR -gt 10 ]]; then # echo "Variable is greater than 10." # fi 

Многострочные комментарии в Bash

В отличие от большинства языков программирования, Bash не поддерживает многострочные комментарии.

Самый простой способ написать многострочные комментарии в Bash — это добавить отдельные комментарии один за другим:

# This is the first line. # This is the second line. 

Другой вариант — использовать HereDoc . Это тип перенаправления, который позволяет передавать команде несколько строк ввода. Если блок HereDoc не перенаправлен на команду, он может служить заполнителем многострочных комментариев:

 Everything inside the HereDoc body is a multiline comment MULTILINE-COMMENT 

Использование HereDoc — это хитрость, а не настоящий встроенный способ написания многострочных комментариев Bash. Чтобы избежать проблем, лучше использовать однострочные комментарии.

Выводы

Написание комментариев является хорошей практикой и помогает другим разработчикам, в том числе будущим самим себе, понять сценарий оболочки. В Bash все, что находится после решетки ( # ) и до конца строки, считается комментарием.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How to use single and multiple line comments in BASH

Using comments in any script or code is very important to make the script more readable. Comments work as documentation for the script. The reader can easily understand each step of the script if the author properly comments on it. Comments are ignored when the script executes. The single line can be commented on very easily in the bash script. But there are multiple ways to comment on multiple lines in the bash script. How you can use single and multiple lines comments in bash scripts is shown in this tutorial.

Single line comment:

You can explain the function of each line of the script by adding a single line comment on the above or side of the line. ‘#’ symbol is used to comment on a single line in the bash script. The following example shows the use of single-line comments. The script will calculate the sum of two integer numbers, and the value of the addition will be printed. The single-line command has been added before each script line that will be ignored after executing the code.

Example-1: Single line comment

The ‘#’ symbol is used to add single-line comments in the bash script. Create a bash script with the following code to check the way to add a single-line comment in the script. Two numeric numbers will be added and printed after executing the script. Here, all comments have been added before each line of the script to describe the purpose.

#!/bin/bash
#Print a simple text
echo «Working with bash comments»
#Add 10 with 20 and store the value in n
( ( n = 10 + 20 ) )
#Print the value of n
echo $n

Output:
The following output will appear after executing the above code.

Example-2: Inline comments in bash script

The single-line comment can also be added after the end of the script that is called an inline comment. Create a bash file with the following script to check the use of inline comments. The following script will combine two string values and print the combined value. Four inline comments have been added in the script that will be ignored at the time of execution.

str1 = «Linux» # Initialize the first string value
str2 = » Hint» # Initilaize the second string value

str = $str1 $str2 # Combine the string values
echo «The string value after concatenating the strings»
echo $str # Print the combined string

Output:
The following output will appear after executing the above code.

Multiple line comment:

There is no direct option to comment on multiple lines in the bash script like other programming languages. You can use other features of bash to comment multiple lines in a script. One option is using ‘here document’, and another option is using ‘:’. The uses of both options are shown in the following examples.

Example-3: Multi-line Comment using here document

#!/bin/bash
This script is used to
Calculate the cube of
a number with value 5
LongComment
#Set the value of n
n = 5
#Calculate 5 to the power 3
( ( result = $n * $n * $n ) )
#Print the area
echo $result

Output:
The following output will appear after executing the above code.

Example-4: Multi-line comment using ‘:’ command

Using colon (:) with the single quote is the most simple way to add a multi-line comment in bash script. The multi-line comment will be added within a single quote(‘) after the colon(:). The use of multi-line comments has shown in the following example. The script will check a number is odd or even. Here, one multi-line comment has been used in the script to describe the script’s main purpose.

#!/bin/bash
#Initialize the variable n with a number
n = 15
: ‘
The following script will check the number is
Even or odd by dividing the number by 2 and checking the remainder value

echo -n » $n »
if ( ( $n % 2 == 0 ) )
then
echo «is a even number.»
else
echo «is an odd number.»
fi

Output:
The following output will appear after executing the above code.

Example-5: Comment multiple lines in Visual Studio Code

The ways to add a comment in multiple lines at a time using ‘#’ in Visual Studio Code has shown in this example. The ways of adding comments in previous examples can be applied to all types of editors. But if you are using any standard code editor like Visual Studio Code, commenting multiple lines or removing the comment from multiple lines is easier than a normal text editor. You have to install this editor in your system to check this example. Create a bash file with the following script using the visual studio code editor.

#!/bin/bash
echo «Working with bash comments»
( ( n = 10 + 20 ) )
echo $n

read -p «Enter the first number: » n1
read -p «Enter the second number: » n2
echo $ ( ( n1+n2 ) )

Select the lines you want to comment out, right-click on the selected lines, and select Add line comment from the command palette.

After the selection, the selected lines will be commented with ‘#’ like the following image.

Select the lines that you want to uncomment out and right-click on the selected lines, and select Remove Block Comment from the command palette to remove the ‘#’ from the lines that were commented before.

Conclusion:

Different ways to add single and multi-line comments in bash script have been shown in this tutorial by using multiple examples. Adding multi-line comments is not simpler in bash like other programming languages when using a text editor. This tutorial will help you learn and apply single and multiple line comments in your bash script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью
Adblock
detector