Is there a simple way to comment out a block of code in a shell script?
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).
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.
In Vim:
shift-V
(enter visual mode), up down highlight lines in block:s/^/#/
the command will look like this:
:'<,'>s/^/#
hit enter
e.g.
shift-V
jjj
:s/^/#
<enter>
Another mode is: If your editor HAS NO BLOCK comment option,
DONE
it WORKS with ANY editor
Use : '
to open and '
to close.
For example:
: '
This is a
very neat comment
in bash
'
This is from Vegas's example found here
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.