DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Michael has posted 7 posts at DZone. View Full User Profile

Inline Comments In Windows Batch Files.

08.22.2009
| 29222 views |
  • submit to reddit
        It is annoying, albeit not a show-stopper, to have to comment things in batch files with rem statements in the line before it.  People used to comments being whitespace (i.e. any programmer of almost any programming language ever written) find line-oriented comments distracting as they break up control flow.  Wouldn't it be nice if you could do in batch files what people using real programming languages take for granted?

You can.

Modern implementations of CMD.EXE start by default with "Command Extensions" enabled.  Earlier ones had to have them enabled.  Thus, to make your batch files work in any environment from Windows 2000 onward, make sure the following line is in your script near the beginning:

VERIFY BADVALUE 2> NUL
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 ECHO Unable to enable command extensions.

(More realistically you'd likely either fall back to more limited scripting capabilities or jump to an error routine that prints that error message and exits.)

That done, you now have a lot of freedom in your comments because in recent CMD.EXE implementations the "::" string is basically a synonym for "rem".

:: - This is a line-oriented comment.
:: - In fact all comments in batch scripts are line-oriented.
:: - How does one make this something you can put at the end of a line?

Well, that's done now.  Making this an inline comment involves a stupid cheap trick.  Remember that in Windows you can string commands together with the "&" operator (similar to how you'd do the same thing in UNIX shells with ";").  Thus you can make saner comments in your code that look something like this:

:: - This comment explains a block of code.
ECHO Here we do something pretty mundane.
ECHO %PATH:\=\\%> JUNK.TXT        &:: This line is a bit weird; we should comment it.
ECHO This is pretty mundane stuff again.

See the trick?  We used the & operator to start a new command and used :: as a comment.  This gives us the illusion of inline comments like C++'s "//" or the Bourne Again Shell's "#".  Of course we could do the same trick with the old "REM" command, but in my opinion this is more distracting than useful.  Take a look.  Your mileage may vary.

:: - This comment explains a block of code.
ECHO Here we do something pretty mundane.
ECHO %PATH:\=\\%> JUNK.TXT        &REM This line is a bit weird; we should comment it.
ECHO This is pretty mundane stuff again.

If this doesn't bother you, you can use it in place of "::" and have your scripts be more universally supported.  Personally, though, I find that less readable than using line-oriented comments.