奇怪的 CMD 批处理脚本报告 %errorlevel%
在下面的脚本中,当出现 sql 错误时,%errorlevel%
为 0 - 这是为什么?
IF %RELEASE% GTR 2 (
(
echo WHENEVER SQLERROR EXIT FAILURE
echo @release.sql
echo exit
) | sqlplus x/x@orcl
echo error: %errorlevel%
if %errorlevel% gtr 0 goto dberror
)
如果我删除 if 块(如下),则 %errorlevel% 不为零!为什么if语句会影响错误级别?
(
echo WHENEVER SQLERROR EXIT FAILURE
echo @release.sql
echo exit
) | sqlplus x/x@orcl
echo error: %errorlevel%
if %errorlevel% gtr 0 goto dberror
更新:相信这是我测试错误的方式。我认为而不是:
if %errorlevel% gtr 0 goto dberror
..应该使用:
if errorlevel 1 goto dberror
有用的链接这里
In the script below, when there is a sql error, %errorlevel%
is 0 - why is this?
IF %RELEASE% GTR 2 (
(
echo WHENEVER SQLERROR EXIT FAILURE
echo @release.sql
echo exit
) | sqlplus x/x@orcl
echo error: %errorlevel%
if %errorlevel% gtr 0 goto dberror
)
If I remove the if block (below) then %errorlevel% is NON zero! Why does the if statement affect the error level?
(
echo WHENEVER SQLERROR EXIT FAILURE
echo @release.sql
echo exit
) | sqlplus x/x@orcl
echo error: %errorlevel%
if %errorlevel% gtr 0 goto dberror
Update: Believe it was the way I was testing for an error. I think instead of:
if %errorlevel% gtr 0 goto dberror
.. should be using:
if errorlevel 1 goto dberror
Useful link here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
叹。这一切都与可怕的 dos 解析以及 cmd 用它的值替换
%errorlevel%
的点有关。当您用(
...)
括起命令时,cmd 首先读取这些命令,就像它们全部写在一行上一样,从而扩展变量就这样。因此,在第一个代码块中,%errorlevel%
在解析该块时被其值替换。。就好像您写道:(假设
$RELEASE
为 3)。您的if errorlevel
修复起作用的原因是cmd
不会对该重新制定进行任何(太)早期的变量扩展。您可以使用call
来避免这个问题:(我认为这比
startlocal ENABLEDELAYEDEXPANSION
和!errorlevel!
- 当然是 YMMV 更清晰)。Sigh. It's all to do with the horrible dos parsing, and the point at which cmd replaces
%errorlevel%
with its value. When you enclose commands with(
...)
, cmd first reads in those commands as though they were all written on one line, expanding variables as it goes. Thus in your first code block,%errorlevel%
is replaced by its value when the block is parsed. It's as if you wrote:(assuming
$RELEASE
was 3). The reason yourif errorlevel
fix works is thatcmd
does not do any (too) early variable expansion on that re-formulation. You can usecall
to avoid this problem:(which I think is clearer than
startlocal ENABLEDELAYEDEXPANSION
and!errorlevel!
—YMMV of course).