· batch-scripts dos command-line

If Else statements in batch files

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.

12345~</td>
  
IF "%1"=="."  (  set WORKING_DIRECTORY=%cd%) ELSE (  set WORKING_DIRECTORY=%1)~</td>
</tr></table>

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:

123~</td>
  
IF "%1"=="" GOTO usageIF [%1]==[] GOTO usage~</td>
</tr></table>

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

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket