17

In a shell script I have the following code:

if echo Mr.32 ; then
  echo Success
else
  echo Failed
  exit
fi

What is the equivalent syntax for Windows batch files?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222

2 Answers2

30

I'm having a hard time envisioning when ECHO would fail with a returned ERRORLEVEL not equal 0. I suppose it could fail if the output has been redirected to a file and the target drive is full.

CptHammer has posted a good solution using ERRORLEVEL, although it uses GOTO unnecessarily. It can be done without GOTO using:

ECHO Mr.32
if errorlevel 1 (
  echo Failed
  exit /b
) else (
  echo Success
)

There is a simpler way to take action on SUCCESS or FAILURE of any command.

command && success action || failure action

In your case

ECHO Mr.32&& (
  echo Success
) || (
  echo Failed
  exit /b
)
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • 2
    If Errorlevel 1 (commandgroup1) else (commandGroup2) will execute commandGroup1 for ANY return code above 1. (i.e. : CommandGroup1 is Failur and CommandGroup2 is Success) – cptHammer Aug 08 '12 at 10:36
  • "command && success action || failure action" This is a very good answer to this question. Thanks for the help! – Matt P Jun 24 '15 at 12:30
  • For an `ELSE IF X ()` is it needed to reparenthes the else? Ex: `ELSE ( IF X() )` – Sandburg Sep 12 '19 at 08:22
  • 1
    @Sandburg - No, that is not needed. – dbenham Sep 12 '19 at 11:52
12

I think something like this might do the trick:

REM run the command
ECHO Mr.32
IF ERRORLEVEL 1 GOTO failLabel

:successLabel
REM put code to execute in case of success here.
ECHO Success
GOTO endLabel

:failLabel
REM put code here that should be executed in case of failure.
ECHO Failed

:endLabel

This assumes the command you want to test (here: echo MR.32) returns 0 on success and anything higher on failure (BEWARE : Echo in most windows OS will return nothing and therefore, the actual value that is tested in this script is probably the return code from the last command executed just before the script. you're probably better of testing with the command : " DIR someFile.txt" that will return 0 if somefile.txt exists and 1 otherwise.)

It is true as dbenham pointed out, that this structure uses lot of GOTO. This is because this GOTO structure is the only one that will be understood fine in all windows versions. More compact versions appeared with time but they will only work on recent windows versions.

cptHammer
  • 440
  • 2
  • 12
  • In most windows versions, Echo command returns nothing. therefore, if the last issued command before the script execution failed, this will give the failed message. on the other hand, if the last command executed before this script was a success, you would get the success message. – cptHammer Aug 08 '12 at 07:51