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?
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?
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
)
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.