Block Comments in a Shell Script
Asked Answered
V

15

344

Is there a simple way to comment out a block of code in a shell script?

Vespers answered 3/6, 2009 at 23:53 Comment(1)
Interesting how such easy and simple question has too different and complicated answers.Disaffection
M
438

In bash:

#!/bin/bash
echo before comment
: <<'END'
bla bla
blurfl
END
echo after comment

The ' and ' around the END delimiter are important, otherwise things inside the block like for example $(command) will be parsed and executed.

For an explanation, see this and this question.

Mezzosoprano answered 4/6, 2009 at 0:2 Comment(19)
Cute trick - as long as the 'END' keyword (which is, of course, user chosen) does not appear on a line on its own inside the material to be commented out.Tented
Very nice trick. BTW, This should work in any Bourne compatible shell as well.Childhood
@JonathanLeffler what do you mean by "which is, of course, user chosen"? That I can use any string I choose in place of END?Bryon
@kalengi: Yes; the word used in the quotes can be anything convenient; EOF is a classic example (and so is !, an exclamation mark on its own), but you could use SNURFLE_BURGERS or classical_end_marker or any other word that doesn't appear on a line on its own in the commented-out material. I'd be leary of experimenting with spaces etc, but the word might well work with them too.Tented
(Works if one removes the single quotes, however.)Barely
Interestingly enough, Emacs on mac actually recognizes echo before comment : <<EOF and automatically inserts the block with a new line and and EOF at the end if the script you are working in is already saved as .sh .Elga
It definitely works but can anyone elaborate on how this works? ThanksGroundling
@MB_CE, see #32127153. That said -- it's running a command (:) that doesn't read its input and always exits with a successful value, and sending the "comment" as input. Not much to it.Herbal
@HotLicks, generally, "shell script" these days refers to POSIX sh derivatives. csh isn't one, so only answers to questions specifically tagged csh can be expected to work with it.Herbal
@JonathanLeffler, "SNURFLE_BURGERS"? I saw somebody else use that same string in another thread on commenting shell scripts. Is there a story behind that?Solander
@DuncanC: I have no recollection of why or how I came up with "snurfle burgers" in that comment. AFAICR, I have not used the term before or since.Tented
You're famous: codextechnicanum.blogspot.com/2013/11/…Solander
I consider it incredibly ugly and confusing to write active code to create passive code... just use good old block select mode and press #; what's the big issue with that?Ferbam
thanks for the tip with the quotes. I was pulling my hair wondering why the commands inside the "commented" section still executed!Cockboat
Complex answer to a simple question. Best answer would be # before any lineStoneblind
I found a script that does basically that, but without the : (that is just <<'EOF' ... ... .. EOF and it seems to work as well. I don't understand why.Bovid
@Ferbam it is sometimes your only choice if you are dealing with programs you cannot completely control. example is an isql client for sybase IQ which cannot suppress (N rows affected) message. If you need sql query to produce bash code then you can make sure your SELECT output begins with close comment and ends with open comment...Uralian
This has the advantage that in an editor which color-highlights here-docs (I use jEdit, I assume other editors do the same thing) the "commented" block is colored differently from "normal" code.Achelous
Great! I've been using the if [[ 1 -eq 0 ]] until now, but this is much better. Thanks!Governess
A
119

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

This is from Vegas's example found here

Ambuscade answered 28/6, 2019 at 4:35 Comment(4)
hack-ish, but awesomePrimitivism
it is the best one for me.Dworman
Easiest to remember.Bodrogi
One problem is that these multi-line strings will end if you happen to have a string-ending ' in there.Flop
S
109

There is no block comment on shell script.

Using vi (yes, vi) you can easily comment from line n to m

<ESC>
:10,100s/^/#/

(that reads, from line 10 to 100 substitute line start (^) with a # sign.)

and un comment with

<ESC>
:10,100s/^#//

(that reads, from line 10 to 100 substitute line start (^) followed by # with noting //.)

vi is almost universal anywhere where there is /bin/sh.

Swarm answered 4/6, 2009 at 0:28 Comment(5)
Nice trick with regular expression on vi to place # in front of lines.Giselagiselbert
Just a tip - if you're using vim and this ends up highlighting the beginning of every line, add |noh to the end. The pipe separates additional commands and noh is for nohighlight. Search term highlighting will automatically resume the next time you search for something. Example: :10,100s/^/#/g|nohConative
I need this to be automated from a script. Is there a way to do that to a file with vi without needing human interaction?Cheerio
@TimothySwan I imagine the gawk or sed program could do that... somehow.Wheeler
my preferred way of commenting (or prefixing) a block with vi: go to beginning of the line you want to start commenting (e.g. <SHIFT>+G 10 <ENTER> then 0 or by any other way to navigate). Then use <CTRL>+V to enter visual block mode and highlight the beginning of all lines you want to comment (in this example 90 J). Then press SHIFT+I to insert before the highlighted block. Enter the comment sign (e.g. #) and press <ESC> to finish your prefixing. This explanation sounds super long, but in my experience it is much faster in practice.Impeccant
G
63

You can use:

if [ 1 -eq 0 ]; then
  echo "The code that you want commented out goes here."
  echo "This echo statement will not be called."
fi
Gash answered 10/4, 2013 at 15:26 Comment(4)
This is classic, but as https://mcmap.net/q/81501/-block-comments-in-a-shell-script notes, just if [ ]; also works.Bottoms
Perhaps clearer: if false;. https://mcmap.net/q/82456/-is-there-a-quot-goto-quot-statement-in-bashJosey
This only seems to only work is the commented text is actually code. I run into problems with comments with pipes and semicolons. Sunny256 answer worked.Reynolds
even more concise would be [ ]; using test that isBrunei
G
32

The following should work for sh,bash, ksh and zsh.

The blocks of code to be commented can be put inside BEGINCOMMENT and ENDCOMMENT:

[ -z $BASH ] || shopt -s expand_aliases
alias BEGINCOMMENT="if [ ]; then"
alias ENDCOMMENT="fi"

BEGINCOMMENT
  echo "This line appears in a commented block"
  echo "And this one too!"
ENDCOMMENT

echo "This is outside the commented block"

Executing the above code would result in:

This is outside the commented block

In order to uncomment the code blocks thus commented, say

alias BEGINCOMMENT="if : ; then"

instead of

alias BEGINCOMMENT="if [ ]; then"

in the example above.

Gunslinger answered 16/10, 2013 at 16:58 Comment(0)
S
30

if you can dodge the single quotes:

__='
blah blah comment.
'
Stannfield answered 15/10, 2013 at 7:23 Comment(5)
I like this. What does the double underscore mean though? As best as I can tell it's just a variable name using the convention that it should be treated as private?Ait
Also provides syntax highlighting in most editors and is callable if needed with $__ though I would suggest a variable name like documentation or docs for clarity.Edithe
You can also append the word local in front ref hereEdithe
This should be the best answer. Just put some dummy variable name instead of the double underscoresLanguor
Tried this, but failed because there was a -F';' inside of the block to comment out.Westlund
A
16

In Vim:

  1. go to first line of block you want to comment
  2. shift-V (enter visual mode), up down highlight lines in block
  3. execute the following on selection :s/^/#/
  4. the command will look like this:

      :'<,'>s/^/#
    
  5. hit enter

e.g.

shift-V
jjj
:s/^/#
<enter>
Alas answered 4/6, 2009 at 0:30 Comment(2)
To uncomment use :s/^#/Rook
Check @horta's answer: https://mcmap.net/q/81501/-block-comments-in-a-shell-script - there are even less key presses!Chemoreceptor
S
5

You could use Vi/Vim's Visual Block mode which is designed for stuff like this:

Ctrl-V  
Highlight first element in rows you want commented  
Shift-i  
#  
esc  

Uncomment would be:

Ctrl-V  
Highlight #'s  
d  
l  

This is vi's interactive way of doing this sort of thing rather than counting or reading line numbers.

Lastly, in Gvim you use ctrl-q to get into Visual Block mode rather than ctrl-v (because that's the shortcut for paste).

Shier answered 6/2, 2015 at 23:2 Comment(1)
Love this simplistic method. :o)Chemoreceptor
F
5

In all honesty, why so much overengineering...

I consider it really a bad practice to write active code for generating passive code.

My solution: most editors have block select mode. Just use it to add # to all lines you want to comment out. What's the big deal...

Notepad example:

To create: Alt - mousedrag down, press #.

To delete: Alt-mousedrag down, shift-right arrow, delete.

Ferbam answered 27/2, 2017 at 15:35 Comment(2)
User most likely is in terminal. Cannot assume a mouse environment.Feaster
Do they still exist? I usually edit in graphical mode and paste back in using vi, that would be an easy workaround.Ferbam
A
3

You can put the code to comment inside a function. A good thing about this is you can "uncomment" by calling the function just after the definition.

Unless you plan to "uncomment" by calling the function, the text inside the function does not have to be syntactically correct.

ignored() {
  echo this is  comment
  echo another line of comment
}

Many GUI editors will allow you to select a block of text, and press "{" to automatically put braces around the selected block of code.

Adequacy answered 6/8, 2021 at 5:17 Comment(0)
E
2

A variation on the here-doc trick in the accepted answer by sunny256 is to use the Perl keywords for comments. If your comments are actually some sort of documentation, you can then start using the Perl syntax inside the commented block, which allows you to print it out nicely formatted, convert it to a man-page, etc.

As far as the shell is concerned, you only need to replace 'END' with '=cut'.

echo "before comment"
: <<'=cut'
=pod

=head1 NAME
   podtest.sh - Example shell script with embedded POD documentation

etc.

=cut
echo "after comment"

(Found on "Embedding documentation in shell script")

Easygoing answered 15/2, 2017 at 11:4 Comment(0)
R
2

I like a single line open and close:

if [ ]; then ##
    ...
    ...
fi; ##

The '##' helps me easily find the start and end to the block comment. I can stick a number after the '##' if I've got a bunch of them. To turn off the comment, I just stick a '1' in the '[ ]'. I also avoid some issues I've had with single-quotes in the commented block.

Roxannroxanna answered 8/3, 2020 at 15:50 Comment(0)
L
1

Let's combine the best of all of these ideas and suggestions.

alias _CommentBegin_=": <<'_CommentEnd_'"

as has been said, the single quote is very important, in that without them $(commandName) and ${varName} would get evaluated.

You would use it as:

_CommentBegin_
echo "bash code"
or 
none code can be in here
_CommentEnd_

The alias makes the usage more obvious and better looking.

Leija answered 7/9, 2021 at 6:24 Comment(0)
D
0

Another mode is: If your editor HAS NO BLOCK comment option,

  1. Open a second instance of the editor (for example File=>New File...)
  2. From THE PREVIOUS file you are working on, select ONLY THE PART YOU WANT COMMENT
  3. Copy and paste it in the window of the new temporary file...
  4. Open the Edit menu, select REPLACE and input as string to be replaced '\n'
  5. input as replace string: '\n#'
  6. press the button 'replace ALL'

DONE

it WORKS with ANY editor

Directorial answered 10/9, 2018 at 13:23 Comment(0)
O
0

This can be done in a shorter syntax in sh, bash and ksh

<< COMMENT

They worked in the cold, so we could be warm,
some died in the evening, some died at dawn.
They breathed in the coal dust, so kids would be fed,
Gone are those miners, all of them dead.


COMMENT
Oxytetracycline answered 29/7, 2023 at 22:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.