Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have an IF block in DOS batch file?

In a DOS batch file we can only have 1 line if statement body? I think I found somewhere that I could use () for an if block just like the {} used in C-like programming languages, but it is not executing the statements when I try this. No error message either. This my code:

if %GPMANAGER_FOUND%==true(echo GP Manager is up goto Continue7 ) echo GP Manager is down :Continue7 

Strangely neither "GP Manager is up" nor "GP Manager is down" gets printed when I run the batch file.

like image 236
Hugh Darling Avatar asked Feb 13 '11 09:02

Hugh Darling


1 Answers

You can indeed place create a block of statements to execute after a conditional. But you have the syntax wrong. The parentheses must be used exactly as shown:

if <statement> (     do something ) else (     do something else ) 

However, I do not believe that there is any built-in syntax for else-if statements. You will unfortunately need to create nested blocks of if statements to handle that.


Secondly, that %GPMANAGER_FOUND% == true test looks mighty suspicious to me. I don't know what the environment variable is set to or how you're setting it, but I very much doubt that the code you've shown will produce the result you're looking for.


The following sample code works fine for me:

@echo off  if ERRORLEVEL == 0 (     echo GP Manager is up     goto Continue7 ) echo GP Manager is down :Continue7 

Please note a few specific details about my sample code:

  • The space added between the end of the conditional statement, and the opening parenthesis.
  • I am setting @echo off to keep from seeing all of the statements printed to the console as they execute, and instead just see the output of those that specifically begin with echo.
  • I'm using the built-in ERRORLEVEL variable just as a test. Read more here
like image 158
Cody Gray Avatar answered Oct 20 '22 18:10

Cody Gray