Add Inline Comments for Multi-line Command in Bash Script

In Bash script, it is common that multiple small commands run together connected by pipes (|) and the whole command is quite long. For clarity, we may write the command in multiple lines. How to add comments for these long multi-line commands? In Bash, the content after # in a line is the comment. Using a single comment line before the multi-line command is not convenient as the command may be quite complex. The best way is still inline comments as we do in many other programming languages. In this post, we discuss 2 techniques used in 2 different scenarios.

Inline comments for multi-line pipe-connected commands

For pipe-connected commands, we use the interesting feature of bash that the pipe | connects 2 subshells and the subshells can have empty lines before it. So we can add a comment after the | and a new line then the next command. One example is as follows.

echo -e "Aabcbb\nAabcbD\nAabcbb" |  # generate the content
     tr a-z A-Z |                   # translate to upper case
     sort |                         # sort the text
     uniq                           # remove duplicated lines

Grammatically, the commend at the end of each line after | is actually part of the next command. But it is natural for readers of the script to consider the comment to describe the command before the |. Cool, right?

Inline comments for multi-line commands separated by <newline>

Now, we don’t have the nice grammar help from the |. We need the techniques making use of the command substitution feature. The command of the subshell can include comment too and the comment ends at the end of the subshell command. So, a command as follows is valid and the comment in the substitution command can be considered as the “inline comment” for that line.

perl -0777 `# whole input as a block` \
 -p `# loop and print line also` \
 -e 's|<PRE>[\s{<BR>}{<HR>}]*</PRE>||g' 

But note that this technique is expensive because it creates a subshell for each of such “inline comments” during execution. It is only suitable if the commands performance or cost is not a problem.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *