424

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
*/`

How could I do that?

Enes Malik Turhan
  • 4,342
  • 3
  • 9
  • 9

12 Answers12

761

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'
Vegas
  • 8,017
  • 1
  • 10
  • 14
  • 47
    :( and also adds a great amount of un-read-ability and potential bug-source. IMHO is better just use multiple `#`s and **never** this... – clt60 Apr 01 '17 at 14:57
  • 95
    @jm666 IMHO Never a good idea to use the word _never_ when you have no idea of all the use cases. – Winter Aug 09 '17 at 17:29
  • 39
    to explain: `:` is shorthand for `true` and `true` does not process any parameters. (manual page: `SYNOPSIS true [ignored command line arguments]` – phil294 Sep 14 '17 at 21:06
  • 89
    The space between `:` and `'` is important – a06e Mar 09 '18 at 16:40
  • 57
    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. – JohnMudd Apr 20 '18 at 19:21
  • 8
    I will just go with `: '''` and `'''` (three ' as in python) – Thamme Gowda Jun 12 '18 at 01:40
  • 11
    If you use this to comment out code, and the code has a `'`, then the comment ends too soon, at that `'`. Even if it's already in a one-line #-style comment! – Camille Goudeseune Jun 26 '18 at 15:39
  • 1
    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. P.S. > This may work according to the syntax highlighting, but fails when running. – PyTis Oct 05 '18 at 03:50
  • 3
    @ThammeGowda nice, but it doesn't work exactly like in Python. A single ' inside the "comment" will still break things. – Perl Ancar Jan 15 '19 at 04:36
  • 3
    In general I'd recommend the heredoc (quoted variant) because it's clearer and does not break so easily. – Perl Ancar Jan 15 '19 at 04:36
  • 1
    @PyTis bear in mind that votes can change the relative order of answers so "the one below" may become wrong. Better use "answer by @name" (can't remember if the mention gets converted internally to user ID - I think it does - if not and author changes their name in their settings then such mentions become dangling... only sure way is a URL to the answer). – Oliver Jan 15 '19 at 13:03
  • 2
    `'` is not safe in this "comment" block – yurenchen Sep 25 '21 at 23:45
  • 1
    Not safe and broke unexpectedly for me. Agree with others who say that HEREDOC answer is better. – logidelic Mar 23 '22 at 13:05
  • A major benefit to all other solutions is that most of current syntax highlight tools (for bash syntax) can recognise an unclosed single quote ' . We are in need of syntax highlight libraries for more accurate colourising of bash syntax. – Sohail Si Apr 16 '22 at 13:16
197

Multiline comment in bash

: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines.  Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2 
comment3
END_COMMENT
Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
David Okwii
  • 7,352
  • 2
  • 36
  • 29
  • 9
    This works, currently accepted answer does not (for me). – Freek May 23 '18 at 07:57
  • 6
    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. – Nux Jun 21 '18 at 13:15
  • 2
    @Freek need to add space – magor Aug 21 '18 at 15:35
  • 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. – PyTis Oct 05 '18 at 03:49
  • 'this is comment in BASH', to make it multiple line, just hit your Enter as long as the sentence ends with ' as well. – Infinite Loops Oct 07 '18 at 08:22
  • @Freek did mazs' comment help? I'm wondering why it doesn't work for you – Nathan majicvr.com Nov 28 '18 at 01:13
  • It's been a while, I could well have been that space indeed. – Freek Nov 28 '18 at 15:14
  • @PyTis couldn't reproduce it. I pasted the above code to a shell script and it worked. Perhaps if you could share the error message you got. – Perl Ancar Jan 15 '19 at 04:18
  • @t.y couldn't agree more. Although it's a few characters more, the END_COMMENT tokens (or something alike) makes it much clearer that the block between is a comment. plus this is not messed up as easily by one single quote. I do it sometimes in Perl too, although with a decent text editor it's not much hassle to just add # to each line in a selection. (M-x comment-region in emacs). – Perl Ancar Jan 15 '19 at 04:21
  • 1
    Good tests in your example. The leading `:` is not necessary. Just start with `<<`. – wisbucky Jul 10 '19 at 21:06
  • You need to **make sure** that the `'END_COMMENT'` has quotes around it. This works `<<'END_COMMENT'` – Akaisteph7 Oct 17 '22 at 18:11
71

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:

<<'###BLOCK-COMMENT'
line 1
line 2

line 3
line 4
###BLOCK-COMMENT

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

<<'###BLOCK-COMMENT'
something something ${FOO{}} something
more comment
###BLOCK-COMMENT

ls

You could of course just use

set -e

<<'###'
something something ${FOO{}} something
more comment
###

ls

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

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 ${FOO{}} 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.

Oliver
  • 27,510
  • 9
  • 72
  • 103
  • 1
    Ah, this one is easy/clean enough to remember! – Thamme Gowda Jun 28 '18 at 01:09
  • 1
    As the previous answer notes, aside from backquotes, $(...) sequence will also be expanded as both forms are command substitution. – Perl Ancar Jan 15 '19 at 04:32
  • "Both are hacks so they could break scripts in the future." Could you expand on this? Although hacks semantically, syntactically they are valid and should not break in the future, unless bash decides to go berserk and breaks heredocs. – Perl Ancar Jan 15 '19 at 04:34
  • @perlancar If we agree that hacks are solutions that use a language / lib feature that is completely unrelated to the problem (like using a heredoc for a comment, or using a parameter on a do-nothing command like `true`), then even if they don't risk breaking (heredoc approach doesn't, but colon version does), 1) hacks still obfuscate the intent: without the first line hinting about multiline comment, most would scratch their head wondering what that code is doing; and 2) have unexpected dark corners (like having to double a quote, quote the heredoc marker in certain cases, etc). – Oliver Jan 15 '19 at 12:48
  • @Oliver : If unquoted, variables **can** have nasty side effects. Imagine that you have embedded in your _heredoc_-comment a string such as `${FOO:=bar}` or `${FOO{}}`. The first may have the side effect to create and set the variable `FOO`, the second will raise a _bad substitution_ error; both effects you would not expect from a real comment. – user1934428 May 19 '20 at 06:56
  • @user1934428 and @ perlancar the single quote version does not support substitutions – Oliver May 19 '20 at 11:17
  • @Oliver : Yes, and this is a good thing: We don't want substitutions. But you wrote _ Even with set -o verbose and $variables mentioned in the comment, quoting the marker is not necessary_, and this is not correct: If you don't (single-)quote the heredoc marker, you do have substitutions in your heredoc. – user1934428 May 19 '20 at 11:45
  • Because of course you don't create an enviroment variable in that way (I never said so), but just a variable. You have to do a `echo $FOO` to see the effect. – user1934428 May 20 '20 at 07:41
  • @user1934428 well I didn't think so but you said "The first may have the side effect to create and set the variable". Anyways I've substantially updated the post. – Oliver May 23 '20 at 02:58
  • @Oliver: Great. It is important to observe the difference between variables and environment variables (i.e. exported variables). The latter is not so easy to accidentally create. – user1934428 May 23 '20 at 08:09
  • 1
    In all of this great info and discussion -- _Nowadays any good editor allows you to press ctrl-/ or similar, to un/comment the selection._ In my case: ctrl Q. Sadly, I never figured this out for myself. – grantiago Apr 06 '21 at 15:38
44

After reading the other answers here I came up with the below, which IMHO makes it really clear it's a comment. Especially suitable for in-script usage info:

<< ////

Usage:
This script launches a spaceship to the moon. It's doing so by 
leveraging the power of the Fifth Element, AKA Leeloo.
Will only work if you're Bruce Willis or a relative of Milla Jovovich.

////

As a programmer, the sequence of slashes immediately registers in my brain as a comment (even though slashes are normally used for line comments).

Of course, "////" is just a string; the number of slashes in the prefix and the suffix must be equal.

noamtm
  • 12,435
  • 15
  • 71
  • 107
7

I tried the chosen answer, but found when I ran a shell script having it, the whole thing was getting printed to screen (similar to how jupyter notebooks print out everything in '''xx''' quotes) and there was an error message at end. It wasn't doing anything, but: scary. Then I realised while editing it that single-quotes can span multiple lines. So.. lets just assign the block to a variable.

x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"

ls -l
date

'
Nikhil VJ
  • 5,630
  • 7
  • 34
  • 55
  • Just no need to assign it to a variable, which **is** a side effect we would not expect from a 'comment'. Replace the `x=` by a `: ` and you have the same effect with no side effect. The only drawback is that the comment then must not contain a single quote. That's why I prefer the usage of a quoted heredoc: With this, the commenter can choose a suitable termination string as he likes. – user1934428 May 20 '20 at 07:47
6

what's your opinion on this one?

function giveitauniquename()
{
  so this is a comment
  echo "there's no need to further escape apostrophes/etc if you are commenting your code this way"
  the drawback is it will be stored in memory as a function as long as your script runs unless you explicitly unset it
  only valid-ish bash allowed inside for instance these would not work without the "pound" signs:
  1, for #((
  2, this #wouldn't work either
  function giveitadifferentuniquename()
  {
    echo nestable
  }
}
Imre
  • 322
  • 3
  • 8
5

in plain bash to comment out a block of code i do

:||{ block of code }

Just Saying
  • 51
  • 1
  • 1
4

Here's how I do multiline comments in bash.

This mechanism has two advantages that I appreciate. One is that comments can be nested. The other is that blocks can be enabled by simply commenting out the initiating line.

#!/bin/bash
# : <<'####.block.A'
echo "foo {" 1>&2
fn data1
echo "foo }" 1>&2
: <<'####.block.B'
fn data2 || exit
exit 1
####.block.B
echo "can't happen" 1>&2
####.block.A

In the example above the "B" block is commented out, but the parts of the "A" block that are not the "B" block are not commented out.

Running that example will produce this output:

foo {
./example: line 5: fn: command not found
foo }
can't happen
bugi
  • 123
  • 1
  • 1
  • 6
4

Simple solution, not much smart:

Temporarily block a part of a script:

if false; then
    while you respect syntax a bit, please
    do write here (almost) whatever you want.
    but when you are
    done # write
fi

A bit sophisticated version:

time_of_debug=false # Let's set this variable at the beginning of a script

if $time_of_debug; then # in a middle of the script  
    echo I keep this code aside until there is the time of debug!
fi
xerostomus
  • 466
  • 4
  • 11
2

After read all solutions prior to 2023.03.25, I use this solution. The benefit of it:

  1. Support nested comment.
  2. Support comment out some multi-line comment by prefix with #
  3. Readable.
  4. Allow single quote in comment.
  5. Pass shellcheck

The cons:

  1. The last command exit code will be reset as zero before comment.
  2. vim color syntax still can not detect it correctly.
  3. longer(but readable).

Here is the example of "disable COMMENT1" and "enable COMMENT2".

#!/bin/bash

echo "line 1"
#: <<'#END_COMMENT1'
echo "line 2"
echo "line 3"
false
: <<'#END_COMMENT2'
echo "line 4"
echo "line 5"
#END_COMMENT2
echo "status code=$?"
#END_COMMENT1
echo "line 6"

output

line 1
line 2
line 3
status code=0
line 6

If you care about the exit code side effect, use the single line comment like

echo "line 1"
echo "line 2"
echo "line 3"
false
#echo "line 4"
#echo "line 5"
echo "status code=$?"
echo "line 6"

output

line 1
line 2
line 3
status code=1
line 6
Daniel YC Lin
  • 15,050
  • 18
  • 63
  • 96
1

Here Documents

<<EOF & EOF solution

#!/usr/bin/env bash

echo "just use the \`EOF\` for multi-line comments in your shell script. "

<<EOF
  comment1
  comment2 
  comment3
  # ...
EOF

By the way: you can also rename EOF to other unique name, such SHELL_MULTI_LINE_COMMENTS.

#!/usr/bin/env bash

echo "just use the \`SHELL_MULTI_LINE_COMMENTS\` for multi-line comments in your shell script. "

<<SHELL_MULTI_LINE_COMMENTS
  comment1
  comment2 
  comment3
  # ...
SHELL_MULTI_LINE_COMMENTS

test ✅


#!/usr/bin/env bash

echo "just use the \`EOF\` for multi-line comments in your shell script. "

<<EOF
  comment1
  comment2
  comment3
  # ...
EOF

echo "just use the \`SHELL_MULTI_LINE_COMMENTS\` for multi-line comments in your shell script. "

<<SHELL_MULTI_LINE_COMMENTS
  comment1
  comment2
  comment3
  # ...
SHELL_MULTI_LINE_COMMENTS

$ chmod +x ./multi-line-comments.sh

$ ./multi-line-comments.sh
just use the `EOF` for multi-line comments in your shell script. 
just use the `SHELL_MULTI_LINE_COMMENTS` for multi-line comments in your shell script. 

screenshots

enter image description here

fefs

https://en.wikipedia.org/wiki/Here_document

https://tldp.org/LDP/abs/html/here-docs.html

xgqfrms
  • 10,077
  • 1
  • 69
  • 68
0

Not even if you use the inner apostrophe, this method does not allow the following content:

: '
' => &#39;
(') => &#39;
'

The best is the shortest:

<</
' => &#39;
(') => &#39;
\/ or #/
/

clarke
  • 21
  • 2