Lets say we want to create an empty file in windows with the following command:
type nul > C:\does\not\exist\file.txt
the directory does not exist, so we get the error:
The system cannot find the path specified
If you print out the %errorlevel%
the output is:
echo %errorlevel% 0
Yet the command was not successful!
I noticed, that windows does not set the %errorlevel%
of the last command if you use redirection..
Is there a way around this?
Batch file error level: %ERRORLEVEL% is an environment variable that contains the last error level or return code in the batch file – that is, the last error code of the last command executed. Error levels may be checked by using the %ERRORLEVEL% variable as follows: IF %ERRORLEVEL% NEQ 0 ( DO_Something )
In Microsoft Windows and MS-DOS, an errorlevel is the integer number returned by a child process when it terminates. Errorlevel is 0 if the process was successful. Errorlevel is 1 or greater if the process encountered an error.
The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.
You can use the following:
C:\>type nul > C:\does\not\exist\file.txt && echo ok || echo fail The system cannot find the path specified. fail C:\>echo %errorlevel% 1
I always assumed the && and || operators used ERRORLEVEL, but apparently not.
Very curious that ERRORLEVEL is set after redirection error only if you use the || operator. I never would have guessed. Nor would I ever have bothered to test if not for your excellent question.
If all you want to do is set the ERRORLEVEL upon redirection failure, then of course you can simply do:
type nul > C:\does\not\exist\file.txt || rem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With