summaryrefslogtreecommitdiff
path: root/src/content/en/til/2026/09/05/multiline-sh-comments.adoc
blob: 13fef6dd286d8d54009509b334076b96764491c9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
= Multiline comments in POSIX sh
:categories: sh

:posixsh: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_07_04


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

[source,sh]
----
cat <<'COMMENT' > /dev/null
if wip; then
	unfinished and broken syntax >
fii
COMMENT
----


...instead of:

[source,sh]
----
# if wip; then
#	unfinished and broken syntax >
# fii
----


What is going on: the {posixsh}[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:

[source,sh]
----
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!

[source,sh]
----
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