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

时间:2018-11-21 00:08:53

标签: windows batch-file

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

@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 个答案:

答案 0 :(得分:3)

%扩展(因此扩展正常的环境变量(例如%VAR%)和命令行参数(例如%0)是读取一行后的第一步,因此甚至在识别rem命令之前就发生了。因此,您需要避免使用%~(例如,通过编写rem % + ~ ...)。

鉴于启用了command extensions,这仍然是默认设置,因此%~被识别为无效的参数语法(~后面应有一个十进制数字来表示参数位置或有效的修饰符,例如fdpnx等;请参见Command Line arguments (Parameters)),结果为致命错误,表示抛出错误消息并中止批处理文件(尽管%ErrorLevel%未设置)。

尝试执行sub-string substitution但指定空的搜索字符串(如%VAR:=replace%%VAR:*=replace%(假定已定义VAR)时,也会产生相同的效果,启用了命令扩展名。

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

答案 1 :(得分:3)

我认为,很多文档中都明确指出cmd将在注释之前解释参数,请参阅@LotPings注释中的示例以及@aschiphl的帖子。话虽如此,您可以暂时disableextensions,然后在需要时将其重新打开。以下示例显示了禁用它如何使您可以在REM注释中使用它,然后在显示允许扩展后再次启用它:

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