代码之家  ›  专栏  ›  技术社区  ›  codesniffer

批处理脚本解释注释中的内容?

  •  4
  • codesniffer  · 技术社区  · 6 年前

    当我运行以下批处理脚本时:

    @echo off
    REM %~ will strip surrounding quotes if any
    
    echo HERE
    

    我得到以下错误:

    C:\>test.cmd
    The following usage of the path operator in batch-parameter
    substitution is invalid: %~ will strip surrounding quotes if any
    
    For valid formats type CALL /? or FOR /?
    

    相同的效果 REM 改为 :: .

    似乎解析器忽略了注释指示器并分析 %~ .如果我在 % ~ 然后就可以了。

    Windows 7 Enterprise(未检查任何其他版本)。

    在我看来像个虫子,但我错过了什么吗?

    2 回复  |  直到 6 年前
        1
  •  3
  •   aschipfl    6 年前

    这个 % -扩展,因此扩展正常环境变量(如 %VAR% )以及命令行参数(如 %0 )是读完一行后的第一步,因此它甚至发生在 rem 命令被识别。因此你需要避免 %~ (通过书面形式 rem % + ~ ... 例如)。

    鉴于 command extensions 已启用,这是默认值, %~ 被识别为无效的参数语法 ~ 应后跟表示参数位置的十进制数字或类似的有效修饰符 f , d , p ,请 n , x 等;参见 Command Line arguments (Parameters) )并导致致命错误,这意味着抛出错误消息并中止批处理文件处理 %ErrorLevel% 但未设置)。

    当你试着去做的时候,同样的效果也会出现。 sub-string substitution 但是指定一个空的搜索字符串(如 %VAR:=replace% %VAR:*=replace% ,鉴于 VAR 也可以启用命令扩展。

    另请参阅此线程: How does the Windows Command Interpreter (CMD.EXE) parse scripts?

        2
  •  3
  •   Gerhard    6 年前

    我认为在相当多的文档中,cmd会很清楚地解释注释之前的参数,参见@lottings comment和@aschiphl的文章中的示例。既然这样说,你可以暂时 disableextensions 必要时再打开。下面的示例显示如何禁用它将允许您在 REM 注释,然后在显示允许扩展后再次启用:

    @echo off
    setlocal disableextensions
    REM %~ will strip surrounding quotes if any"
    endlocal
    echo my batch file is %~0