Question

Batch files: comments in multi-line blocks

Asked by: markar100

This isn't so much of a question as a notation of odd behavior.  I have always assumed that the batch interpreter interprets multi-line blocks as a single line as follows:

if [%1]==[] (
  echo No parameters!
  goto :EOF
)

gets interpreted as
if [%1]==[] ( echo No parameters! & goto :EOF)

For this reason, comments in a multi-line block would be a problem:
if [%1]==[] (
  rem Handle incorrect call
  echo No parameters!
  goto :EOF
)
becomes
if [%1]==[] ( rem Handle incorrect call & echo No parameters! & goto :EOF)

which obviously causes the commands after the comment to be treated as a comment.  I am pretty sure that this was how things worked in WinNT.

However, this no longer seems to be the case in WinXP, so I have started commenting like I would in any programming language (copiously, that is).  So far so good.  I use the :: for comments instead of rem because it looks better and because it is a little more efficient, since the processor doesn't have to interpret the line.  So now we have

if [%1]==[] (
  ::Handle incorrect call
  echo No parameters!
  goto :EOF
)

Everything still works, although if you leave echo on, you can see that the batch processor doesn't even acknowledge the existence of the comment (unlike REMed comments).  The problem came up when I happened to put two comments in a row within a multi-line block.

if [%1]==[] (
  ::Handle incorrect call
  ::Tell the user, then quit
  echo No parameters!
  goto :EOF
)

Now I get an obscure message that says
The system cannot find the drive specified.

The batch file still executes correctly, I just see this error message whenever there are two :: comments in a row.  Replacing either :: with rem fixes the problem.  Placing a command between the comments fixes the problem.  Placing an empty line between the comments causes an incorrect syntax error which stops the whole batch file.

This problem is easy enough to work around, and might be commonly known, although I couldn't find any previous questions about it.  I guess I'm just posting this as a warning, since it took me an hour or so to figure out what was causing the problem (it was in the middle of a moderately complex batch file).  It takes quite a while before you start to think about your comments as a possible cause of a problem, and even then, it took a while before I realized it wasn't the particular text in the comments.  

I am curious as to what the batch interpreter is seeing when I do this. If anyone can shed some light on the issue, I would be interested.

Thanks,
Mark

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-07-01 at 21:55:55ID21045653
Tags

batch

,

line

,

multi

,

files

,

comments

Topic

MS DOS

Participating Experts
4
Points
125
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. mouse_event to obscured window
    I am making a magnify app, I am trying to make it so you can click in the magnified view and send mouse data ( via mouse_event ) to the window under the cursor ( in my view ). It seems to work but in cases where the magnify view is over the window being magnified the mouse ev...
  2. What does this @rem mean?
    Hi At the top of a perl script, I see this @rem. Looks like comments, but I know comments start with #. So what does this mean? Thanks. Jirong @rem = ' PERL for Windows NT -- ccperl must be in search path @echo off ccperl %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 goto endofperl @rem '...
  3. BATCH FILE
    Hi Does anyone know how to fire a PHP script using a BATCH file? Thanks
  4. Batch File
    Hi... I'm trying to create a batch file that is supposed to check a directory for specific file extensions and then delete them or move them to a different folder. After that it is supposed to send a message to the administrator or send an email to the administrator. Is t...
  5. REM Line More defined
    I am writing a batch file and don't like the REM line set out from the path name. I would like the REM line to be more like a Title or Explaination of a Process so that it is real clear to the user what it is doing. How can I accomplish this?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: sirbountyPosted on 2004-07-01 at 21:59:28ID: 11454081

Interesting info - thanx for sharing...I believe we have a couple of die-hard DOS gurus here that might be able to shed some light on this...if you don't mind, I'll sit back and watch. :D

 

by: SteveGTRPosted on 2004-07-02 at 06:53:01ID: 11456681

I don't use the :: as comments, but I've seen them used before.

As for how the command interpreter processes batch files internally, I won't make any guesses. It does however have a problem with :: in if statements.

I ran a test on both NT2000 and XP Profession and REM worked just fine in any combination from within the if statement.

I did run into problems when I did the following:

if 1==1 (
  ::Test1
  ::Test2
  echo Test
)

This results in "The system cannot find the drive specified." on both XPPro and NT2000.

if 1==1 (
  ::Test1
  echo Test
  ::Test2
)

This results in ") was unexpected at this time." on both OS's.

The following work just fine:

if 1==1 (
  REM Test1
  REM Test2
  echo Test
)

if 1==1 (
  REM Test1
  echo Test
  REM Test2
)

Good Luck,
Steve

 

by: markar100Posted on 2004-07-02 at 15:19:28ID: 11460600

Yeah, I did find that REM always works.

So the rules about :: comments in multi-line blocks seem to be:

1. Don't use two :: lines in a row - "The system cannot find the drive specified."
2. Don't use a :: as the last line in a block - ") was unexpected at this time."
3. Don't use a :: followed by an empty line - "The syntax of the command is incorrect."

It does seem like we may have enough clues to figure out what is going on here.


If you are interested, here's another little puzzle:
Enter the single line batch file:
if [1]==[1] (rem test)

When you run it you'll see a blank line followed by two prompts:
c:\temp>test

c:\temp>
c:\temp>

 But if you put an empty line at the start of the batch file, before the single line, you'll see:
c:\temp>test
c:\temp>c:\temp>

I'm sure this is a result of how unbalanced paretheses are handled, since the closing paren is not seen after the REM.  You can prove this by putting a closing paren on the next line, and everything works as expected. However, echo is on, so you would expect to see a blank line show up BEFORE it hits the IF line, so somehow the shell is backing up a couple of times as it tries to extricate itself from the batch file.

Useless info, I'm sure.

Mark

 

by: SteveGTRPosted on 2004-07-02 at 15:28:50ID: 11460650

Interesting.

I'm grateful to even have the if... Even though you do have to be careful. I like this one:

@echo off

if 1==1 (
  echo test 1

Doesn't print a thing. The unclosed paren error :) Done that one before, more than once.

 

by: K_2KPosted on 2004-07-03 at 13:44:14ID: 11464900

Those symptoms are side effects of the normal recreation of the script inside  ( ) as a separate process.

First of all,  starting a line with two colons is technically NOT a "comment" as a rem statement is.
The REM statement is parsed at run time like any other statement or command is.

The first colon on any line is actually telling the parser this is NOT a statement, but a label, and it is treated as any other label.  The second one makes this a label with no name or a "null label", but that does not change the normal treatment of labels, that is to identify the name of the label in the first word and ignore the rest of the line.  This is why some sites state that using null labels at the beginning of lines for comments is faster and more efficient than the REM statement.  Certain characters can mess up the REM statement without messing up a null label line.  Yes I believe them that the null label is faster since the line is not parsed, but i've never timed and calculated the difference to prove it and CERTAINLY never had enough REM statements to see performance improvements even when the REMs were completely deleted, but theory is more fun to talk about than reality.

So, now if i want a label inside a parens routine, it would have to be quoted if supported at all, and i've never bothered to try, but i suppose this might work:
:: setup flags for if
set flag1=true
set flag2=2
:: run the routine only if
if "%flag1%"=="true" (
 ^:^: run the thing
  echo flag was true
  goto inner%flag2%
  ^:inner1
  echo this should not run when flag2 is 2
  goto ^:innerend
  ^:inner2
  echo this should run when flag2 is 2
  goto ^:innerend
  ^:innerend
  )
 

Again, that's just speculation and i've never found a viable purpose to give me reason to try it,   i simply use real rem statements inside perens when i feel documentation is needed, and keep the null labels outside.


(\o/)  Hope this helps,
2K

 

by: K_2KPosted on 2004-07-03 at 13:55:17ID: 11464920

Here's one I HAVE tried and run into often that demonstrates another side effect of the routine being parsed completely before it is run:

:: setup flags for if
set flag1=true
set flag2=2
:: run the routine only if flag1 is active
if "%flag1%"=="true" (
  REM do some math
  set /a flag2=%flag2% + 1
  echo "Result of flag2 + 1 is not %flag2%"
  )
  echo "Result of flag2 + 1 is %flag2%"

Note that inside the parens both the echo and the set commands were parsed with the same value of %flag2% expanded before any execution of the routine, so the first result line will have been expanded to the value of flag2 before it ran the set.  The usage of flag2 outside the routine shows that flag2 was changed by set even though the first echo would not see it when it ran - it's variables including %flag2% were already expanded so it did not know to check any variables for a change.

See SETLOCAL /? and read about ENABLEDELAYEDEXPANSION for more information on this behavior in the language of Microsoft jibberish.

(\o/)  Have fun,
2K

 

by: markar100Posted on 2004-07-03 at 18:41:08ID: 11466048

Hello 2K,

Thanks for the input.  I assume that everyone on this thread understands delayed and non-delayed expansion, since I've seen answers from most of you on the subject.

Regarding comments, it is very clear that null labels ARE supported within multi-line blocks, and they are supported like usual (no escaping necessary).  If you leave echo turned on, you'll see that the :: lines don't show up at all (unlike REM lines). And, as long as you follow the three rules I stated above, everything works as expected.  Commented lines are not seen, other lines are executed.

I very much agree that this is a result of how parens are processed, although I wouldn't agree with your wording that they are a separate process, as "process" has a well-defined meaning to an operating system.  What I'm looking for is a  description of how the paren processing interferes with the label processing, or vice versa.

Some combination of the paren processing and the label processing leads to the errors.  All the errors seem to relate to the line AFTER the null label.  To me, it looks like there is special code that examines the line after a label, maybe to make sure the label is a reasonable target for a goto.  Or lines after a label are executed without checking that we're in a block.  Somehow, this post-label-checking code runs before the code that would determine the next line is itself a label.  Maybe something about how the paren processing handles the lines in the block confuses this code.

I've always thought of paren processing as moving all the lines in the block up onto a single line and placing &'s between them.
if 1==1 (
echo Test
do something
)
becomes
if 1==1 echo Test & do something

And I've thought of label processing as just ignoring everything up to the line feed. But these models don't explain the behaviour completely.

My thought is that if we can determine a more accurate model for what is going on, there might be more little caveats to worry about like the three rules above.  But mostly this is just idle curiosity. We probably won't know the answer unless some MS programmer publishes a tell-all book.

Thanks for all the input, more theories are welcome,
Mark

 

by: BigDavyPosted on 2005-07-22 at 10:35:03ID: 14504836

FYI, I ran into a similar problem with multi-line comments in July 2005.  I wasn't able to locate the question/answer above, so I posted a new question at

http://www.experts-exchange.com/Operating_Systems/MSDOS/Q_21498411.html

Go there for additional discussion but the conclusion is the same, i.e. "::" is unreliable for comments and REM will work better.

I'm adding this comment so the two questions are cross-referenced for anyone with this problem in the future.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...