Solved %errorlevel% goto problem batch file

March 22, 2014 at 04:12:11
Specs: Windows 7
Hi all,

Not particularly advanced in batch file scripting but just trying my hand. Having a bit of an issue with the following script:

Echo on
findstr /i "test" "c:\test\Test.txt" || if %errorlevel% EQU 1 goto notfound
findstr /i "test" "c:\test\Test.txt" || if %errorlevel% EQU 0 goto found

:notfound
start X.exe
goto done

:found
start Y.exe
goto done

:done
exit

I'm probably doing something stupid, but the original "goto" seems not to work?

Basically, what I want to happen is if the file located at c:\test\test.txt contains the word "text" then Y.exe starts, and if it doesn't, then X.exe starts.

Any assistance would be greatly appreciated.

Thanks,


See More: %errorlevel% goto problem batch file

Report •


#1
March 22, 2014 at 05:20:02
findstr /i "test" "c:\test\Test.txt" && if %errorlevel% EQU 0 goto found
:notfound
echo start X.exe
goto done
:found
echo start Y.exe
goto done

:done

::mike


Report •

#2
March 22, 2014 at 20:24:16
In a series of commands separated by logical pipes ("||",logical FALSE, "&&",logical TRUE), any successive command's execution depends on the outcome of the previous (ie: errorlevel). If the previous command has errorlevel zero, the next command will execute if joined by "&&", and not execute if joined by "||". Opposite holds for errolevel non-zero: next command WILL execute if ||, not if &&. So your test for errorlevel is built-in to these logical pipes. F/E:
echo MY TEST | FIND "MY TEST" && echo string was found || echo not found
echo MY TEST | FIND "Mxyz" && echo string was found || echo not found
And you can combine them, but only if you do the AND (&&) first:
echo MY TEST | FIND "MY TEST">NUL && echo string was found || echo not found
You do not need to use errorlevel at all, but if you do, you should eliminate the logical opoerators "||" and "&&" because these do the same thing, and combining both (%errorlvel% and the booleans) muddies the waters. Pick one approach and go with it, but don't try to use both. "||" following a command, means OR (errorlevel nonzero). "&&" means AND (errorlevel zero)

Report •

#3
March 24, 2014 at 12:50:01
✔ Best Answer
findstr /i "test" "c:\test\Test.txt" || if %errorlevel% EQU 1 goto notfound

Yeah, what nbrane said. To be clear, what you're doing here is looking for "test". If it fails AND the command before this findstr returns 1, you goto notfound. Otherwise, you don't. Probably not what you want, especially when ECHO doesn't modify errorLevel.

How To Ask Questions The Smart Way

message edited by Razor2.3


Report •
Related Solutions


Ask Question