Question

FOR command gives error, but only when using colons for comments

Asked by: BigDavy

I am getting the error message "The system cannot find the drive specified." when I use multiple comment lines in the "do" portion of a "for" line in my batch file.  OS is Windows Server 2003 and also happens on Windows XP.

I am using "::" to precede comments, which some sites recommended rather than "rem".  (including http://www.experts-exchange.com/Programming/Q_20241272.html)

Below is an example:

@echo off
for %%D in (hi) do (
echo Before a comment
::Comment 1
::Comment 2
echo After a comment
)

Output is:
Before a comment
The system cannot find the drive specified.
After a comment

If I omit Comment 2, it's fine (no error).  If I omit Comment 1, it's fine.  If I use "rem" for my comments, it's fine.

I can use "rem" to avoid the error, but I'd like to find out why it's happening, if anyone knows or has seen this before....  Perhaps it's just an undocumented (?) limitation of using colons for comments?

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
2005-07-20 at 09:39:28ID21498411
Tags

batch

,

get

Topic

MS DOS

Participating Experts
6
Points
500
Comments
12

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. Removing Colons in Filenames in a Directory
    I am attempting to replace colons with periods in all the filenames within a particular directory. I tried using SED in the following way: ls | sed 's/:/./gw *' However, this did not save the files under the new name containing periods instead of colons. Obviously I've ...
  2. What's the syntax for IF command with colon(:) notati…
    What's the syntax for IF command with colon(:) notation (used in scripts, not datawindows) ?
  3. What's the syntax for IF command with colon(:) notati…
    What's the syntax for IF command with colon(:) notation (used in scripts, not datawindows) ?
  4. Truncating semi-colon
    I have tried to run a .sql file against the database (Oracle 9i), however upon execution, some of the database objects seem to be invalidated. This is due to the truncation of a semi-colon at the end of a statment. So for example, a trigger would look something like this: ...
  5. Batch file wierdness: full colon remarks ":: a comment…
    On my computer a full colon remark within a parenthesis block will cause a drive not found or an unexpected close error. What happens on your computer? Do you get the same results? What do you think is going on? Is this a bug? This will fail: ... do ( echo HI!...

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: leewPosted on 2005-07-20 at 09:45:37ID: 14486593

Colons are not meant for comments.  They are meant for defining goto points.  If it executes faster as the poster in the EE comment said, I suspect it's only because it's misinterpreting things.  I would use the REMs.  I have never otherwise heard that :: is faster than REM - besides, faster is relative.

 

by: leewPosted on 2005-07-20 at 11:31:33ID: 14487764

I think it's important to point out that XP uses cmd.exe, not command.com by default.  The second link simply sites "easier to read" as the reasoning for use ::.  If you are having problems with :: then I suggest it's because it wasn't designed to be a remark character.  It happens to be usable at times, but it would stand to reason to me that using : as a remark character would actually slow things down because the batch file would have to remember what every instance of : said in order to use it to "goto" when appropriate or if not remember, then have to reread the file whenever a goto was encountered.  REMs should be ignored entirely.

 

by: BigDavyPosted on 2005-07-20 at 13:28:15ID: 14489077

Thanks for the responses.  I've used double-colons in other spots in my script with no problems.

 

by: SunBowPosted on 2005-07-20 at 18:45:19ID: 14490879

I agree with leew, adding that comments have no place embedded in loops for any language, whether you think they are ignored or not. Use comments to explain blocks of code, or like headers/subheaders.

Stick three comments just before the loop if you want that many lines to make something clear (the next block of lines). For transportability (across platforms and versions) try to stick to standards everyone knows and uses, and avoid gimmicks.

Since colons are for labeling, using for other purposes adds clutter not to mention confusion. The 2nd colon usually identifies the first character as the drive, and nless mistaken here, isn't colon one of the original 32 drives of dos?

 

by: SteveGTRPosted on 2005-07-20 at 19:13:21ID: 14491027

Here my two cents.

I'm not a fan of the double colon comments. They appear to mostly work although it's not a documented feature. In the case of the code blocks you can run into problems (as you found out).

You can even replicate your problem by saying:

(
:: Comment A
:: Comment B
)

As SunBow inferred the processing for the code block appears to get confused by the 2nd :: comment and thinks that you're referring to some drive. Like if you were to type in a drive letter and colon for an unmapped drive letter. On my machine, if I type w: I get the same error:

"The system cannot find the drive specified."

I've often read where people prefer :: for comments because of the execution speed and have never given it a 2nd thought. Until now, that is.

I created two batch files one with 10,000 REM statements and the other with 10,000 :: statements. The template for the code looked like this:

@echo off
echo Start>time.txt
REM Test
echo End>>time.txt

On my machine the REM statements executed in 4.18 seconds and the :: statements executed in 2.19 seconds. That is almost twice as fast in favor of the :: comments.

But, how many comments do you normally enter in a batch file. I'll comment something that is particularly hairy, but that's about it.

As SunBow stated it is probably better to not add comments inside a code block. The reason I'd give for this recomendation is that if you are doing a loop a large number of times it would probably be better to leave out the extra processing of a comment. Save that for a comment prior to the loop with a code block.

Someone else asked this question and there was a discussion that did look a lot like this thread :)

 

by: K_2KPosted on 2005-07-20 at 20:16:36ID: 14491242

leew is correct in his first post.
The first colon by definition creates a "label" for CALL or GOTO to be able to jump to.
The word after that is the identification of that specific label - must be unique to function correctly.
The second colon closes the identification and everything after that on the line is ignored by the parser.  

Starting with two colons together creates a null label that is useless.  It has interesting side effects of NOT expanding variables included on that line. It's not a statement like REM, it's a nul label with ignored characters after it.   Also special characters that can cause execution errors when used in REM statements do not cause errors when included on a null label line.  REM is a statement and as such is parsed.  That takes more time than ignoring a text on a null label line, but if that very tiny difference is important to you then you need a better languange than batch commands anyway, so feel free to use REM.  

It's the way ( ) sends all encluded lines through a new instance of the CMD interpreter that causes lines beginning with :: to fail.  
I aggree with SunBow -  if at all possible, you should put remarks before the FOR statement to prevent the parser from re-hashing the REM statement during every time the do ( ) loops around.  If your ( ) loop is SOOO long you MUST use explanations inside, then use REM.  

- I wouldn't want to mention the sideeffect of the first interpreter ignoring a third colon as just another character after the nul label and passing it to the loop with the rest of the line.  The (  ) generated interpreter uses colons 2 and 3 as if they are 1 and 2 in the child process. Code like this has been shown to work, but you will not see it in any of my stuff (i hope):
(
echo test 1
::: echo this line ignored - you will not see it echoed.
rem  this works just as well but parses again for each loop
echo done
)

   
leew and sunbow were first with correct answers, - I only added this in hopes of making the difference more clear.

As for second colon implying a drive letter, that's just a human perception thing.  Drive letters are only concidered as such when used in context of a file name, reguardless of weather first on a line or in the middle, or surrounded by quotes.  This demonstrates the interpreter believing in a drive letter that is not a drive letter at all (test.txt and server named test do not need to exist for this to work) :
for %%K in ( C:test.txt  \\test\test.txt ) do echo %%K is on drive: %%~dK


good luck (\o/)

 

by: K_2KPosted on 2005-07-20 at 20:20:44ID: 14491255

Well said Steve,  now we all know i type slow and took at least an hour to get that in there,  lol.
Would you believe i was interrupted several times by a herd of wild horses?

would you believe instead only twice by my lovely wife?

 

by: WallsyPosted on 2005-07-21 at 00:46:37ID: 14491887

Just my two cents:

Does it honestly make that much difference that a REM statement is processed? On an old 386 every cycle counted, but in these days of 3+GHz processors, pretty much anything run in a CMD script runs at blinding speed. Unless it's an:
      Embedded
            Embedded
                  Embedded
                        Remark

I don't think it will cause great pain. Just look at SteveGTR's tests - 10,000 REMs took 2 seconds...

If a batch file takes an age to run, it's probably the commands you're calling, not the remarks.

Wallsy

 

by: BigDavyPosted on 2005-07-21 at 08:57:52ID: 14494295

Hi, thanks for all the responses and insight....

I had previously searched this site and couldn't find the issue in the PAQs, but after SteveGTR said it had been discussed before, I tried again and finally found it here: http://www.experts-exchange.com/Operating_Systems/MSDOS/Q_21045653.html

As for using REM exclusively for comments:

http://www.obrienpc.net/dos/y-rem.html says that REM can screw up batch files when the commented line contains a pipe (|) or redirection (<, >, >>) symbol, at least in DOS 7.  However I tested their example of:

REM echo. | date

and this gave me no problems on WinXP.

So now I plan to use REM all the time.

I agree that the speed issue is not anything to worry about (at least for my tiny scripts).  I mostly liked the colons because my scripts were easier to read!  ;)

Thanks again--

Dave

 

by: SunBowPosted on 2005-07-21 at 16:05:03ID: 14498320

Thanks                            [Good Fortune]

Concerning readability, add at least some extra blank lines. Spaces (tabs..) are also good if conducive to columns. I like a <CR> immediately before and after a series (group) of lines, whether they are of a loop, or comments, or whatever (set variables?)

 

by: SunBowPosted on 2005-07-21 at 16:13:20ID: 14498354

Oh, confession here, I do tend to get in habit also of not only tabbing inside of loops, but of repeating some favorite labels, whether they are needed or not, such as ":done" to give that horizontal break for the general theme of the point of the process. It also reduces debugging a little, by half, when I want a quick and clean jump out of the middle of the program, all that's needed is the goto part. Although I think we (some of us) are correct on the code error being about bad syntax for drive letter, I checked and colon was not among the original six symbols used for that.

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...