Home > Articles > Home & Office Computing > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

Conditional Processing with If

One of the most important capabilities of any programming language is the ability to choose from among different instructions based on conditions the program finds as it runs. For this purpose, the batch file language has the if command.

The Basic If Command

In its most basic form, if compares two strings and executes a command if the strings are equivalent:

if string1 == string2 command 

This is used in combination with command-line variable or environment variable substitution, as in this example:

if "%1" == "ERASE" delete somefile.dat 

If and only if the batch file's first argument is the word ERASE, this command will delete the file somefile.dat.

The quotation marks in this command aren't absolutely required. If they are omitted and the command is written as

if %1 == ERASE delete somefile.dat 

the command will still work as long as some command-line argument is given when the batch file is run. However, if the batch file is started with no arguments, then %1 would be replaced with nothing, and the command would turn into this:

if == ERASE delete somefile.dat 

This is an invalid command. CMD expects to see something before the == part of the command and will bark if it doesn't. Therefore, it's a common practice to surround the items to be tested with some character—any character. Even $ will work, as shown here:

if $%0$ == $ERASE$ delete somefile.dat 

If the items being tested are identical, they will still be identical when surrounded by the extra characters. If they are different or blank, you'll still have a valid command.

The if command also lets you reverse the sense of the test with the not option:

if not "%1" == "ERASE" then goto no_erase 

Checking for Files and Folders

The exist option lets you determine whether a particular file exists in the current directory:

if exist input.dat goto process_it 
    echo The file input.dat does not exist
    pause
    exit /b
:process_it

Of course, you can specify a full path for the filename if that's appropriate, and you can use environment variables and % arguments to construct the name. If the filename has spaces in it, you'll need to surround it with quotes.

The not modifier can be used with exist as well.

Checking the Success of a Program

When a command line or even a Windows program exits, it leaves behind a number called its exit status or error status value. This is a number that the program uses to indicate whether it thinks it did its job successfully. An exit status of zero means no problems; larger numbers indicate trouble. There is no predetermined meaning for any specific values. The documentation for some programs may list specific error values and give their interpretations, which means that your batch files can use these values to take appropriate action. How? Through the errorlevel variation of the if command.

After running a command in a batch file, an if statement of the form

if errorlevel number command 

will execute the command if the previous program's exit status value is the listed number or higher. For example, the net use command returns 0 if it is able to map a drive letter to a shared folder, and it will return a nonzero number if it can't. A batch file can take advantage of this as follows:

@echo off 

net use f: \\bali\corpfiles
if errorlevel 1 goto failed
    echo Copying network data...
    if not exist c:\corpfiles\nul mkdir c:\corpfiles
    copy f:\*.xls c:\corpfiles
    exit /b
:failed
    echo Unable to access network share \\bali\corpfiles
    pause

You can also use not with this version of the if command. In this case, the command is executed if the error status is less than the listed number. The error testing in the previous example can be rewritten this way:

if not errorlevel 1 goto success 
    echo Unable to access network share \\bali\corpfiles
    pause
    exit /b
:success
    echo Copying network data...
    if not exist c:\corpfiles\nul mkdir c:\corpfiles
    copy f:\*.xls c:\corpfiles

In this version, the flow of the batch file is a bit easier to follow. However, even this can be improved upon, as you'll see next.

Performing Several Commands After If

Often, you'll want to execute several commands if some condition is true. In the old days, before the extended CMD shell came along, you would have to use a goto command to transfer control to another part of the batch file, as in the if exist example given in the previous section. With the extended version of if, this is no longer necessary.

The extended if command lets you put more than one statement after an if command, by grouping them with parentheses. For example, you can place multiple commands on one line, as shown here:

if not errorlevel 1 (echo The network share was not available & exit /b) 

Or you can put them on multiple lines:

if not errorlevel 1 ( 
    echo The network share was not available
    pause
    exit /b
)

I recommend the second version, because it's easier to read. Look how much clearer the network file copying example becomes when parentheses are used instead of goto:

@echo off 

net use f: \\bali\corpfiles
if errorlevel 1 (
    echo Unable to access network share \\bali\corpfiles
    pause
    exit /b
)
echo Copying network data...
if not exist c:\corpfiles\nul mkdir c:\corpfiles
copy f:\*.xls c:\corpfiles

You can also execute one set of commands if the if test is true and another if the test is false by using the else option, as in this example:

if exist input.dat echo input.dat exists else echo input.dat does not exist 

You can use else with parentheses, but you must take care to place the else command on the same line as if, or on the same line as the closing parenthesis after if. You should write a multiple-line if...else command using the same format as this example:

if exist input.dat ( 
    echo Sorting input.txt...
    sort <input.txt >source.data
) else (
    echo Input.txt does not exist. Creating an empty data file...
    echo. >source.data
)

Extended Testing

The extended if command lets you perform a larger variety of tests when comparing strings, and it can also compare arguments and variables as numbers. The extended comparisons are listed in Table 12.3.

Table 12.3. Comparison Operators Allowed by the if Command

Variation

Comparison

if string1 EQU string2

Exactly equal

if string1 NEQ string2

Not equal

if string1 LSS string2

Less than

if string1 LEQ string2

Less than or equal to

if string1 GTR string2

Greater than

if string1 GEQ string2

Greater than or equal to

if /i (comparison)

Case-insensitive

if defined name

True if there is an environment variable name.

if cmdextversion number

True if the CMD extensions are version number or higher.

As an added bonus, if the strings being compared contain only digits, then CMD compares them numerically. For example, you could test for a specific exit status from a program with a statement like this:

some program 
if %errorlevel% equ 3 (
    echo The program returned an exit status of 3 which
    echo means that the network printer is offline.
)
  • + Share This
  • 🔖 Save To Your Account