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 [/shell] 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 add 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.
Subscribe to Xmodulo
Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.
Did you find this tutorial helpful? Then please be generous and support Xmodulo!