Block Comments in a Shell Script

Viewed 391217

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

15 Answers

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.

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.

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

This is from Vegas's example found here

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>

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.

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

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.

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.

In vscode ctrl+K+C (ctrl+K+U to uncomment).

Related