Monday, November 14, 2005

Random DOS Nuances: for-loops, params, and if-blocks

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/random_dos_nuances_forloops_params_and_ifblocks.htm]

I've blogged some tips on DOS before, but here are some more. One of my coworkers (thanks Roey) pointed out several DOS nuances that I found useful - they're the kind of things that are easy to miss:

Use single % for parameters (like %1), double %% for variables (like %myVar%)

While you can use environmental variables using the percent signs like so: %myVar%, parameters only have the first percent, like so: %1. What's tedious is if you make it %1%, you may be able to get away with it in some cases. But if you put two parameters on the same like like %1...%2, then you need to get it straight.

Set operators within an if-block don't update until after the if-block finishes

In a language like C#, you could both update the variable, and then use that variable within the same if-block. Apparently you can't do that in DOS.

REM: Won't work:
If 0 EQU 0 (
    set outputFile="ABC"
    Echo Value: %outputFile%
)

You need to let the if-block finish first. You can do this by putting the set operation in its own block, either like this:

REM: WIll work:
If 0 EQU 0 (
set outputFile="ABC"
)
Echo Value: %outputFile%

or like this:

REM: will also work:
If 0 EQU 0 set outputFile="ABC"
If 0 EQU 0 Echo Value: %outputFile%

DOS for-loops in a batch script require an extra '%' in front of the variable.

This will fail:

Rem start loop:
for /F %a in (C:\temp\List.txt) do Echo %a
Pause

This will work:

Rem start loop:
for /F %%a in (C:\temp\List.txt) do Echo %%a
Pause

This last one is especially tedious to debug because if you copy the contents of the script to a command window to run it, then it suddenly works.
 

No comments:

Post a Comment