Windows 中的文件重定向和 %errorlevel% [英] File redirection in Windows and %errorlevel%

查看:32
本文介绍了Windows 中的文件重定向和 %errorlevel%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们想使用以下命令在 Windows 中创建一个空文件:

Lets say we want to create an empty file in windows with the following command:

type nul > C:does
otexistfile.txt

目录不存在,所以我们得到错误:

the directory does not exist, so we get the error:

The system cannot find the path specified

如果你打印出%errorlevel%,输出是:

If you print out the %errorlevel% the output is:

echo %errorlevel%
0

然而命令没有成功!

我注意到,如果您使用重定向,Windows 不会设置最后一个命令的 %errorlevel%..

I noticed, that windows does not set the %errorlevel% of the last command if you use redirection..

有没有办法解决这个问题?

Is there a way around this?

推荐答案

您可以使用以下内容:

C:>type nul > C:does
otexistfile.txt && echo ok || echo fail
The system cannot find the path specified.
fail

C:>echo %errorlevel%
1

我一直假设 &&和 ||操作员使用了 ERRORLEVEL,但显然没有.

I always assumed the && and || operators used ERRORLEVEL, but apparently not.

很好奇只有​​当你使用 || 时才会在重定向错误后设置 ERRORLEVEL操作员.我永远不会猜到.如果不是因为你的好问题,我也不会费心去测试.

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.

如果您只想在重定向失败时设置 ERRORLEVEL,那么您当然可以简单地执行以下操作:

If all you want to do is set the ERRORLEVEL upon redirection failure, then of course you can simply do:

type nul > C:does
otexistfile.txt || rem

这篇关于Windows 中的文件重定向和 %errorlevel%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆