这是常规脚本:
param = args[0]
println(param)
这是我运行它的方式 (Windows 7):
groovy test.groovy a&b
我希望此脚本打印 a&b,但 get 'b' 未被识别为内部或外部命令、可运行程序或批处理文件。
我试图将论点(在我的例子中是 a&b)放在引号中,但没有用。使用双引号,脚本挂起。使用单引号时,我会得到与没有任何引号时相同的错误。
问题: 是否可以将带有 & 符号的字符串作为 groovy 脚本的命令行参数?
最佳答案
在 Windows 上执行 groovy
时,我们实际上执行 %GROOVY_HOME\groovy.bat
然后(从 groovy.bat
):
"%DIRNAME%\startGroovy.bat""%DIRNAME%"groovy.ui.GroovyMain %*
如果我们查看 startGroovy.bat
,我们可以看到一个非常丑陋的 hack 来处理参数(摘录如下):
rem horrible roll your own arg processing inspired by jruby equivalent
rem escape minus (-d), quotes (-q), star (-s).
set _ARGS=%*
if not defined _ARGS goto execute
set _ARGS=%_ARGS:-=-d%
set _ARGS=%_ARGS:"=-q%
set _ARGS=%_ARGS:?=-n%
rem Windowz will try to match * with files so we escape it here
rem but it is also a meta char for env var string substitution
rem so it can't be first char here, hack just for common cases.
rem If in doubt use a space or bracket before * if using -e.
set _ARGS=%_ARGS: *= -s%
set _ARGS=%_ARGS:)*=)-s%
set _ARGS=%_ARGS:0*=0-s%
set _ARGS=%_ARGS:1*=1-s%
set _ARGS=%_ARGS:2*=2-s%
set _ARGS=%_ARGS:3*=3-s%
set _ARGS=%_ARGS:4*=4-s%
set _ARGS=%_ARGS:5*=5-s%
set _ARGS=%_ARGS:6*=6-s%
set _ARGS=%_ARGS:7*=7-s%
set _ARGS=%_ARGS:8*=8-s%
set _ARGS=%_ARGS:9*=9-s%
因此,在 startyGroovy.bat
中,"a&b"
被“escaped”为 -qa&b-q
,导致脚本中有两个命令,产生
'b-q' is not recognized as an internal or external command,
operable program or batch file.
并在“未转义”时导致无限循环。
您可以在运行 groovy 脚本之前使用 set DEBUG=true
查看它。
在一堆 hack 中添加另一个 hack,您还可以在 startGroovy.bat
中以类似的方式转义&
,如下所示:
rem escape minus (-d), quotes (-q), star (-s).
rem jalopaba escape ampersand (-m)
set _ARGS=%*
if not defined _ARGS goto execute
set _ARGS=%_ARGS:-=-d%
set _ARGS=%_ARGS:&=-m%
set _ARGS=%_ARGS:"=-q%
set _ARGS=%_ARGS:?=-n%
和逃脱...
rem now unescape -s, -q, -n, -d
rem jalopaba unescape -m
rem -d must be the last to be unescaped
set _ARG=%_ARG:-s=*%
set _ARG=%_ARG:-q="%
set _ARG=%_ARG:-n=?%
set _ARG=%_ARG:-m=&%
set _ARG=%_ARG:-d=-%
这样:
groovy test.groovy "a&b"
a&b
不确定在 Windows 中是否有更清晰/更优雅的解决方案。
您可以在 groovy -e "println 2**3"
中看到类似的情况,它在 UNIX 控制台中产生 8
但在 Windows 中挂起(无限循环)。
关于windows - Groovy:在命令行参数中使用&符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26763103/