Advertisement
Advertisement


Block Comments in a Shell Script


Question

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

2015/04/11
1
257
4/11/2015 4:13:47 PM

Accepted Answer

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.

2017/06/23
353
6/23/2017 2:17:14 PM

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.

2016/12/02

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
2013/04/10

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.

2013/12/11

if you can dodge the single quotes:

__='
blah blah comment.
'
2013/10/16

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

This is from Vegas's example found here

2019/06/28

Source: https://stackoverflow.com/questions/947897
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]