Robust software, for everybody.


Multiline comments in POSIX sh

Posted on

I realized one can use heredocs for multiline comments in sh:

1
2
3
4
5
cat <<'COMMENT' > /dev/null
if wip; then
        unfinished and broken syntax >
fii
COMMENT

…​instead of:

1
2
3
# if wip; then
#       unfinished and broken syntax >
# fii

What is going on: the language defines << as a redirect of the "here-document" type. After << you can put anything, and sh will use that as a token to look for on the following lines:

1
2
3
cat <<'bleh'
...
bleh

Make sure to include the 'quotes' around the word, otherwise anything with a $ would get replaced just like a "double-quoted" string.

"bleh" works fine, like any word would.

But that example left as-is would print the string to stdout. To avoid that, we shove the contents to /dev/null. So it isn’t technically a comment, its more like a constant string that gets emitted and discarded.

Sure its hacky, but at this point what in sh isn’t? It even supports nesting!

1
2
3
4
5
6
7
8
9
cat <<'COMMENT1' > /dev/null

cat <<'COMMENT' > /dev/null

# ... code ...

COMMENT

COMMENT1

I’ve never committed any code with this, just used while debugging sh code. Make sure to handle with care

4 messages on the fediverse

Reply on Mastodon | Lemmy