How to comment out a block of code in a shell script

Last updated on November 16, 2020 by Dan Nanni

When you are writing a shell script, you often want to comment out some part of your code, instead of throwing it out, especially if you are debugging it. In a shell script, anything following a pound sign # is considered as a comment until the end of the line. So commenting out a single line is easy. What if you want to comment out multiple lines of code, or a block of code in a shell script?

In a nutshell, you can comment out a block of code by using the following syntax.

: <<'MYCOMMENT'
echo "code 1"
echo "code 2"
echo "code 3"
echo "code 4"
MYCOMMENT

Basically you surround a block of code to comment out (from line 2 to 5 in this example) with a pair of : <<'MYCOMMENT' and MYCOMMENT. You can replace the keyword MYCOMMENT with any string. The only requirement is that the keyword string not appear anywhere within the block of code itself.

You can use the same syntax to add multi-line comments in a shell script. You no longer need to prepend a # sign to every line.

The rest of post is for those who want to understand how the hell this weird looking code actually comment things out.

This is something called a here document (or heredoc), which is a special-purpose code block used to get any text data into a script verbatim. A here document is typically used to feed a long multi-line arguments to a command or program (without relying on a separate file), and is called in the following format.

COMMAND <<INPUT_DELIMETER
. . .
. . .
INPUT_DELIMETER

A chunk of string between two instances of INPUT_DELEMETER is fed to COMMAND.

In our case, COMMAND corresponds to :. A colon : sign is a built-in shell command which does nothing with its arguments. So what actually happens is that we feed a verbatim block of code into a dummy : function as its argument. Then of course nothing happens, which essentially means that the block of code just evaporated.

If you find this tutorial helpful, I recommend you check out the series of bash shell scripting tutorials provided by Xmodulo.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean