Home > Posts > Windows 7 Command Line Help mistake for IF command

Windows 7 Command Line Help mistake for IF command

If you type

help IF

at the Windows 7 command-line (can launch this by searching at Windows Start menu search box for “Command” or by typing cmd there and pressing ENTER), you get in one of the help pages printed out for the batch files’ IF command:

%ERRORLEVEL% will expand into a string representation of
the current value of ERRORLEVEL, provided that there is not already
an environment variable with the name ERRORLEVEL, in which case you
will get its value instead. After running a program, the following
illustrates ERRORLEVEL use:

goto answer%ERRORLEVEL%
:answer0
echo Program had return code 0
:answer1
echo Program had return code 1

If a program you launched from the batch file returns error code 0 (meaning usually no error), then you jump to label (using “goto” command) answer%ERRORLEVEL% that is answer0 (labels are prefixed with : in DOS/Windows batch files) and it prints out (using echo command) on the console “Program had return code 0”.

Fine till here, but then it will proceed to next commands (the block labeled :answer1) and also print out “Program had return code 1”. Obviously the correct example should be:

goto answer%ERRORLEVEL%
:answer0
echo Program had return code 0
goto finish
:answer1
echo Program had return code 1
:finish

Could also have a goto finish after the last echo, but its needless since we don’t have :answer2 etc. labels after that and proceeds to finish by itself anyway.

Thinking of this example again, it’s a pretty silly one since one could do instead:

echo Program had return code %ERRORLEVEL%

BTW, to output an empty line to the console you can use echo:
And speaking of batch file tips, you can use :: for comment lines instead of REM command.

Advertisements
  1. 2012/02/26 at 01:17

    good article are when it’s well written, factually accurate and verifiable, broad in coverage, neutral in point of view, stable, and illustrated, where possible, by relevant images with suitable copyright licenses. Good articles need not be as comprehensive as featured articles, but they should not omit any major facets of the topic. you done it well, i like your website, i will following yours. thanks

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: