File redirection in Windows and %errorlevel%

lukuluku picture lukuluku · Apr 27, 2012 · Viewed 7.4k times · Source

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?

Answer

dbenham picture dbenham · Apr 28, 2012

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