Saturday, August 1, 2015

multi-line comments in shell script

The standard and the general practice of newcomers and veteran shell scripters alike is to use the '#' to indicate a comment in shell script. For example:
# this is a comment

and if done carefully, it can be done at end of a line like:
echo yada yada yada # this is a comment

For multiple lines of comments, every line of the comment needs its own '#' at the beginning, like:
# a comment
# more comment stuff
# tedium ... comments yada

If, for whatever your reasons, you don't wish to do a '#' at beginning of every line, then you can do something like this:

#!/bin/bash

echo See http://unix.stackexchange.com/questions/37411/multiline-shell-script-comments-how-does-this-work
echo
echo My example ignores the multi-line comments in the middle of a loop
for thing in one two three
do
  echo Step ${thing}
: <<'<COMMENT'

This is an abuse of the null command ':' and the here-document syntax
to achieve a "multi-line comment".  According to the POSIX spec linked
above, if any character in the delimiter word ("end_long_comment" in
this case) above is quoted, the here-document will not be expanded in
any way.  This is **critical**, as failing to quote the "end_long_comment"
will result in the problems with unintended expansions described above.
All of this text in this here-doc goes to the standard input of :, which
does nothing with it, hence the effect is like a comment.  There is very
little point to doing this besides throwing people off.  Just use '#'.

# just in case previous line escapes the end of line
<COMMENT
  date
  echo
  sleep 1
done
echo after multi line comments

#

This will produce results of:
See http://unix.stackexchange.com/questions/37411/multiline-shell-script-comments-how-does-this-work

My example ignores the multi-line comments in the middle of a loop
Step one
Sat Aug  1 22:18:54 CDT 2015

Step two
Sat Aug  1 22:18:55 CDT 2015

Step three
Sat Aug  1 22:18:56 CDT 2015

after multi line comments

No comments:

Post a Comment

This is Charles Weldon Witt. Thank you for commenting on my blog.