Rac*_*oon 6 windows groovy command-line ampersand windows-console
这是groovy脚本:
param = args[0]
println(param)
Run Code Online (Sandbox Code Playgroud)
以下是我运行它的方法(Windows 7):
groovy test.groovy a&b
Run Code Online (Sandbox Code Playgroud)
我希望这个脚本打印a&b,但是'b'不会被识别为内部或外部命令,可操作程序或批处理文件.
我试图将参数(在我的情况下为a&b)放在引号中,但它没有帮助.使用双引号,脚本挂起.使用单引号我得到相同的错误,如没有任何引号.
问题:是否可以将带有&符号的字符串作为groovy脚本的命令行参数?
groovy在Windows上执行时,我们实际执行%GROOVY_HOME\groovy.bat然后(从groovy.bat):
"%DIRNAME%\startGroovy.bat" "%DIRNAME%" groovy.ui.GroovyMain %*
如果我们查看内部startGroovy.bat,我们可以看到一个非常丑陋的黑客来处理参数(摘录如下):
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%
Run Code Online (Sandbox Code Playgroud)
因此,inside startyGroovy.bat "a&b"被" 转义 "为-qa&b-q,导致脚本中的两个命令屈服
'b-q' is not recognized as an internal or external command,
operable program or batch file.
Run Code Online (Sandbox Code Playgroud)
并且在" unescaping " 时造成无限循环.
您可以set DEBUG=true在运行groovy脚本之前查看它.
添加另劈到的一群黑客,你可以逃脱也&以类似的方式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%
Run Code Online (Sandbox Code Playgroud)
和unescape ...
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=-%
Run Code Online (Sandbox Code Playgroud)
以便:
groovy test.groovy "a&b"
a&b
Run Code Online (Sandbox Code Playgroud)
不确定Windows中是否有更清晰/更优雅的解决方案.
你可以看到类似的情况下groovy -e "println 2**3"能产生8在UNIX控制台,但挂起(无限循环)的窗口.