Using Batch Files, Part 3: The IF Command

by Barry Dysert
(last updated July 28, 2014)

5

This tip continues the series about using batch files. It is suggested that you (re)visit the previous tips so that we can pick up where we left off. Thus far we've covered the following commands: DIR, REM, ECHO, FIND, TIME, and TIMEOUT. We've also used the following operators: output to file (>), remark (::), no echo (@), pipe (|), and concatenate (&). Finally, we know that we use parameters passed to a batch file via the combinations %1, %2, %3, etc.

This tip will focus on commands that are related to performing conditional processing in a batch file. These include IF, CHOICE, GOTO, and the special syntax of ":label".

I have a very handy batch file called Do.bat. It is little more than a "wrapper" that runs programs regardless of where these programs reside. So, for example, if I want to run the program called Prog1.exe I would simply type

C:\Bat> DO Prog1

If I wanted to run Prog2.exe I would type

C:\Bat> DO Prog2

The beauty of Do.bat is that when I created it, I entered the locations of all the programs that I want it to work with. So I don't have to remember, for example, that Prog1.exe lives at "C:\Programs\My Programs\Prog1.exe" and that Prog2.exe lives at "D:\Utilities\Barry\Prog2.exe". Plus, I never have to type those long path names again.

My Do.bat file looks like this:

@ECHO OFF
GOTO %1
:Prog1
"C:\Programs\My Programs\Prog1.exe"
GOTO Done

:Prog2
"D:\Utilities\Barry\Prog2.exe"
GOTO Done
:Done

The first line of the file ensures that the other lines won't be displayed. This is followed by the GOTO line, which takes as a parameter the name of the label that control is to be transferred to. And it so happens that this label is also the parameter that was passed to Do.bat to begin with. So when you invoke Do.bat and pass "Prog1" as the parameter, the .bat file does a GOTO to a label named ":Prog1" (these are not case sensitive). Execution follows sequentially from top to bottom, so the next command to be executed is the one that invokes Prog1.exe. After this program is finished, the .bat file continues by executing the "GOTO Done" command. The ":Done" label is the last line of the file, so when it reaches this point, the .bat file exits. (There is an EXIT command, but if we were to execute that, it would terminate not only the .bat file but also the entire CMD session, which is probably not what you want to do.)

You could alternatively use the CHOICE command and perhaps create a simple menu from which to choose what program to run. In this case I might make a file called Choice.bat which would look like this:

@ECHO OFF
ECHO Select 1 to run Prog1
ECHO Select 2 to run Prog2
ECHO Select Q to quit
CHOICE /C 12Q /T 10 /D Q
GOTO %ERRORLEVEL%
:3
ECHO Quitting
GOTO Done
:2
"D:\Utilities\Barry\Prog2.exe"
GOTO Done
:1
"C:\Programs\My Programs\Prog1.exe"
GOTO Done
:Done

The CHOICE command provides the user with a prompt to enter a 1, 2, or Q (by default, it is not case sensitive). Any other character is ignored. The /T switch says to timeout in 10 seconds, at which time the procedure will behave as if the Q option was selected (/D Q says the Default option is Q). After the CHOICE command executes, the variable %ERRORLEVEL% is set to ordinal value of the option selected. So if the user selected 1, %ERRORLEVEL% is set to 1; if the user selected 2, %ERRORLEVEL% is set to 2; and if the user selected Q, %ERRORLEVEL% is set to 3. We then GOTO the label indicated by %ERRORLEVEL% and perform the requested action.

 This tip (13185) applies to Windows 7 and 8.

Author Bio

Barry Dysert

Barry has been a computer professional for over 30 years, working in different positions such as technical team leader, project manager, and software developer.  He is currently a senior software engineer with an emphasis on developing custom applications under Microsoft Windows. ...

MORE FROM BARRY

Changing How Tasks Appear on the Taskbar

The Windows Taskbar is much more robust than it was in previous versions of the operating system. One of its many features is ...

Discover More

Understanding the Start Menu Search Box

The Start Menu Search Box is a great addition to Windows. It can save you a great deal of time by putting frequently used ...

Discover More

DesktopOK

Are you frustrated by your desktop icons moving around whenever you change your screen resolution or use Remote Desktop? ...

Discover More
More WindowsTips

Running a Batch File at a Scheduled Time

Once you become comfortable with batch files, chances are that you'll want to use them to perform various system maintenance ...

Discover More

Using Batch Files, Part 1

This tip is part of a series that shows you how to create and use Windows batch files. It introduces a few commands and the ...

Discover More

PowerShell Input and Output

When dealing with a scripting language like PowerShell, one of the first things you need to learn is how to get data into and ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in WindowsTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is five more than 2?

2014-07-29 12:19:55

Scott Renz

Thanks, Barry.


2014-07-29 04:54:58

Barry

MWilson,

Have you read the other tips on batch file use? I give some examples where batch files can save you lots of time. As just one example, suppose you want to do various types of disk cleanup every day at 2:00am? You'd likely use a Scheduled Task to invoke a batch file to move, copy, delete files, produce a report, email it to yourself, etc.

Batch files may not be for the average user who can always click their way along, but they're a godsend to folks who perform admin duties on the box.


2014-07-28 19:29:22

MWilson

Barry:

I'm a neophyte about batch file use.

Your example Do.bat seems to run a program from a predefined location.

I think I accomplish the same task by creating a shortcut to that program with a mouse click, drag and drop. I store those "utility" program shortcuts all in a folder on my desktop.

Two mouse clicks activate any of them -- much quicker than creating, typing and running a batch file.

What am I missing in the advantages of a batch file execution?


2014-07-28 12:34:18

Barry

I'm sorry, Scott. I totally spaced that one. I could write an entire tip on IF, but the basics are that you do something like:
IF arg1 operator arg2 command

where 'arg1' and 'arg2' are arguments being tested, 'operator' is one of EQU, NEQ, LSS, LEQ, GTR, GEQ (i.e., EQUal, Not EQual, LeSS than, etc.), and 'command' is a command-line command.

A simple batch file to echo P1 if there is one might look like this:

@echo off
if [%1] equ [] echo No parameter passed
if [%1] neq [] echo Parameter p1 is '%1'
goto :eof

(I got in the habit of using [] around my arguments to avoid certain complications.)

There are other flavors of IF too. For example, you can test an error level, test if a file exists, include an ELSE statement, etc.

At the command line, do a IF /? and you'll get a good idea what all you can do.

Sorry again that I blew the tip by forgetting to talk about IF. If you have any questions, feel free to submit another comment. Thanks.


2014-07-28 12:06:57

Scott Renz

Thank you for these tips. The title says it is about the "IF" command, but I see nothing about the "IF" command in the tips.


Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in WindowsTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.