Commenting out a set of lines in a shell script
Solution 1:
The most versatile and safe method is putting the comment into a void quoted
here-document
, like this:
<<"COMMENT"
This long comment text includes ${parameter:=expansion}
`command substitution` and $((arithmetic++ + --expansion)).
COMMENT
Quoting the COMMENT
delimiter above is necessary to prevent parameter
expansion, command substitution and arithmetic expansion, which would happen
otherwise, as Bash manual states and POSIX shell standard specifies.
In the case above, not quoting COMMENT
would result in variable parameter
being assigned text expansion
, if it was empty or unset, executing command
command substitution
, incrementing variable arithmetic
and decrementing
variable expansion
.
Comparing other solutions to this:
Using if false; then comment text fi
requires the comment text to be
syntactically correct Bash code whereas natural comments are often not, if
only for possible unbalanced apostrophes. The same goes for : || { comment text }
construct.
Putting comments into a single-quoted void command argument, as in :'comment
text'
, has the drawback of inability to include apostrophes. Double-quoted
arguments, as in :"comment text"
, are still subject to parameter expansion,
command substitution and arithmetic expansion, the same as unquoted
here-document contents and can lead to the side-effects described above.
Using scripts and editor facilities to automatically prefix each line in a block with '#' has some merit, but doesn't exactly answer the question.
Solution 2:
if false
then
...code...
fi
false
always returns false so this will always skip the code.
Solution 3:
You can also put multi-line comments using:
: '
comment1comment1
comment2comment2
comment3comment3
comment4comment4
'
As per the Bash Reference for Bourne Shell builtins
: (a colon)
: [arguments]
Do nothing beyond expanding arguments and performing redirections. The return status is zero.
Thanks to Ikram for pointing this out in the post Shell script put multiple line comment