【问题标题】:I can't understand choice error codes of batch我无法理解批处理的选择错误代码
【发布时间】:2018-11-27 23:11:56
【问题描述】:

如果我有这样的代码:

@echo off
choice /C BL /M "Clear screen or list actual directory"

if errorlevel 2 goto l
if errorlevel 1 goto b

:l
tree /f
goto final

:b
cls
goto final

:final

我知道这确实有效,但我对错误级别部分的一件事感到困惑。 我先写了同样的代码,但是是这样的:

if errorlevel 1 goto l
if errorlevel 2 goto b

这样它就不能正常工作它只会记住错误代码1。如果你按第二个选项不起作用。
我真的很想知道为什么错误的顺序很重要,如果一个批次应该逐行执行,还是我错了?
简而言之,我想了解的是错误代码在这里是如何工作的

【问题讨论】:

  • 带有if errorlevel 1 的经典表单实际上被评估为if errorlevel is 1 or greater,因此第一个较低的数字第一个第二个 if 不执行全部。
  • If errorlevel 1 If not errorlevel 2 只会在 1 上触发。
  • 来自 Choice 帮助文件:注意:ERRORLEVEL 环境变量设置为从选项集中选择的键的索引。列出的第一个选项返回值 1,第二个选项返回值 2,依此类推。如果用户按下了无效选择的键,该工具会发出警告哔声。如果工具检测到错误情况,则返回 ERRORLEVEL 值 255。在批处理程序中使用 ERRORLEVEL 参数时,请按降序排列。

标签: batch-file if-statement cmd choice


【解决方案1】:

提示一下,当使用附加到 goto 标签的 %errorlevel% 变量时,事情会变得非常简单:

@echo off
choice /C BL /M "Clear screen or list actual directory"
goto :choice%errorlevel%

:choice1 B
tree /f
goto final

:choice2 L
cls
goto final

:final
pause

【讨论】:

    【解决方案2】:
    C:\>if /?
    ...
    IF [NOT] ERRORLEVEL number command
    ...
    ERRORLEVEL number   Specifies a true condition if the last program run returned
                        an exit code equal to or greater than the number specified.

    换句话说,if errorlevel 1 执行任何错误级别(0 = 无错误除外),因为它们都等于或大于 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多