Weirdness With Echo and Parentheses Within Conditional Statements

The if command in Windows batch files has some strange implications. One problem is that parentheses take on special meaning.

I first ran into this problem because my batch file would terminate shortly after showing, “folder unexpected at this time“.

A very basic if command might look like this:

C:\>if exist C:\ ( echo The C drive exists )
The C drive exists

However, placing parentheses inside the echo statement will entirely confuse CMD:

C:\>if exist C:\ ( echo The C drive exists (no, really) )
) was unexpected at this time.

Well, that sort of makes sense. It becomes confusing when the last word in your echo command is something more general, like the word ‘folder’:

C:\>if exist C:\Windows ( echo Found the Windows (on C:) folder )
folder was unexpected at this time.

This is actually the classic %%i was unexpected at this time error.

One solution is to put double quotes around the message to be echoed:

C:\>if exist C:\Windows ( echo "Found the Windows (on C:) folder" )
"Found the Windows (on C:) folder"

The drawback here is that the double quotes appear in the output. A better option is to use the caret (^) escape character:

C:\>if exist C:\Windows ( echo Found the Windows ^(on C:^) folder )
Found the Windows (on C:) folder

About Jeff Fitzsimons

Jeff Fitzsimons is a software engineer in the California Bay Area. Technical specialties include C++, Win32, and multithreading. Personal interests include rock climbing, cycling, motorcycles, and photography.
This entry was posted in Technology. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *