File redirection in Windows and %errorlevel%

2019-01-03 17:01发布

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?

1条回答
可以哭但决不认输i
2楼-- · 2019-01-03 17:48

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
查看更多
登录 后发表回答