Mark Needham

Thoughts on Software Development

If Else statements in batch files

with 4 comments

I mentioned in a couple of earlier posts that I've been doing quite a bit of work with batch files and the windows command line, and today I wanted to do an If Else statement in one of my scripts.

I thought it would be relatively simple, but after various searches and having read articles that suggested that there wasn't an ELSE construct in batch land I finally found a forum post which explained how to do it.

The script I'm working on takes in a working directory as one of the arguments and what I wanted to do was either set a variable to be the value passed in, or if the value passed in was '.' then to set it to the current working directory.

1
2
3
4
5
IF "%1"=="."  (
  set WORKING_DIRECTORY=%cd%
) ELSE (
  set WORKING_DIRECTORY=%1
)

I played around with this a little bit and it does seem that the brackets need to be in that exact format otherwise it doesn't work at all. Even putting brackets around the IF part of the statement will stop the script from working as expected.

IF statements on their own are much easier to deal with. To check for an empty argument for example either of the following will work:

1
2
3
IF "%1"=="" GOTO usage

IF [%1]==[] GOTO usage

It does all seem a bit fiddly and Powershell is probably the way forwards, but for now batch scripts it is!

Written by Mark Needham

August 13th, 2008 at 10:27 pm

4 Responses to 'If Else statements in batch files'

Subscribe to comments with RSS

  1. Can you not use cygwin?

    Jayesh

    14 Aug 08 at 10:46 am

  2. The reason I'm not using cygwin is because we're using the same script to deploy stuff on different machines e.g. one for QA, one for Showcase etc and for flexibility it seemed easier just to work with the lowest denominator.

    Mark Needham

    14 Aug 08 at 6:37 pm

  3. Mark,

    I'm with you on Cygwin where you need to redistribute the Cygwin binaries. It's painful. I'm betting on dynamic languages.

    Once Iron Ruby has a production release I think it will be very compelling for this kind of thing.

    Something has to put batch programming to bed …

    Julian Simpson

    17 Aug 08 at 8:12 pm

  4. The tip about [] for empty args is really useful, often arguments contain spaces and so you end up with something like this which will break:

    IF ""my 1st argument""=="" GOTO Continue

    Mark Thomas

    27 Aug 08 at 8:24 pm

Leave a Reply