1

这是一个简单的bat文件:

C:\temp>type a.bat
@echo off
rem try
echo %1

有一些困难,我可以a&b作为参数传递给它:

C:\temp>a.bat a&b
a
'b' is not recognized as an internal or external command,
operable program or batch file.
C:\temp>a.bat "a&b"
"a&b"

参数具有"字符;我可以忍受它。但我不知道如何从 cygwin shell 调用它:

C:\temp>c:\cygwin\bin\sh
sh-4.1$ ./a.bat a&b
[1] 7760
a
sh: b: command not found
sh-4.1$ ./a.bat a\&b
a
'b' is not recognized as an internal or external command,
operable program or batch file.
[1]+  Done                    ./a.bat a
sh-4.1$ ./a.bat \"a\&b\"
"\"a
'b\""' is not recognized as an internal or external command,
operable program or batch file.
sh-4.1$ ./a.bat "a\&b"
a\
'b' is not recognized as an internal or external command,
operable program or batch file.
4

1 回答 1

1

Windows CMD 用于^转义大多数特殊字符。因此,您可以使用它来传递您的论点而不用引号括起来。

C:\temp>a.bat a^&b

但接收到的参数将是a&b. 您的批处理脚本在尝试回显 %1 的值时会出错,因为 %1&没有被引用或转义。

如果将值括在引号中,则可以安全地回显该值:

echo "%1"

但是,如果您传递已经包含在引号中的值"a&b",那么您会再次收到错误消息。这就是为什么许多批处理脚本使用~修饰符来删除任何现有的封闭引号(如果它们存在),然后显式添加引号。如果 %1 的值被引用或不被引用,以下将起作用。

echo "%~1"

您仍然可能会遇到类似的问题"a&b"&c,但这是另一回事:-)

另一种选择是&在原始命令行中双重转义:

C:\temp>a.bat a^^^&b

您的批处理脚本将收到a^&b,然后回显将起作用。

关于 Cygwin,我知道的很少,但我相信我主要了解测试 1、2 和 3。

测试1:

sh-4.1$ ./a.bat a&b
[1] 7760
a
sh: b: command not found

Cygwin 正在传递a给您的批处理脚本并且无法执行命令b

测试 2:

sh-4.1$ ./a.bat a\&b
a
'b' is not recognized as an internal or external command, operable program or batch file.

我不确定 CMD 是否在执行批处理脚本之前解析从 Cygwin 传递的命令行。

如果a是这样,则将传递给您的批处理脚本,然后 CMD.EXE 无法执行b

如果不是,那么 Cygwin 正在成功执行您的脚本并传递a&b,但您的 ECHO 语句失败,正如我之前解释的那样。

以下之一应该适用于您的脚本,但我不确定哪个:

sh-4.1$ ./a.bat a^\&b
or
sh-4.1$ ./a.bat a^^^\&b

以上其中一项将通过a^&b,您的 ECHO 应该可以工作。

测试 3:

sh-4.1$ ./a.bat \"a\&b\"
"\"a
'b\""' is not recognized as an internal or external command, operable program or batch file.

我不知道 Cygwin 在做什么。不知何故,它引入了额外的双引号。

测试 4:

sh-4.1$ ./a.bat "a\&b"
a\
'b' is not recognized as an internal or external command, operable program or batch file.

Cygwin strips the quotes, and the backslash is preserved. Again, either the & is causing problems when CMD.EXE is launching the script, or it is causing problems within the script when you ECHO it.

One of the following should work, passing a^&b to your script. I'm just not sure which one:

sh-4.1$ ./a.bat "a^&b"
or
sh-4.1$ ./a.bat "a^^^&b"

I believe the following will successfully pass "a&b" to your script:

sh-4.1$ ./a.bat '"a&b"'

I also think the following will do the same, though I am not as confident due to the result of Test 3.

sh-4.1$ ./a.bat "\"a&b\""
于 2012-10-03T00:22:18.397 回答