【问题标题】:Groovy: using ampersand in command line parameterGroovy:在命令行参数中使用与号
【发布时间】:2015-01-01 23:50:33
【问题描述】:

这是 groovy 脚本:

param = args[0]
println(param)

这是我的运行方式(Windows 7):

groovy test.groovy a&b

我希望这个脚本打印 a&b,但是却得到 'b' 不是内部或外部命令、可运行程序或批处理文件。

我试图将参数(在我的情况下为 a&b)放在引号中,但它没有帮助。使用双引号,脚本挂起。使用单引号我会得到与没有任何引号相同的错误。

问题:是否可以将带有 & 号的字符串作为 groovy 脚本的命令行参数?

【问题讨论】:

  • 该消息是来自 groovy 本身还是来自 Windows shell?在 MacOS 上,它可以通过以下调用完美运行:groovy script.groovy a\&b
  • 转载了它。这是一个 Windows 命令行的东西。有很多建议的修复方法涉及用克拉转义和使用双引号,但似乎都不起作用。
  • 刚刚尝试过groovy test a^&b,但没有成功?您在 Windows 中使用什么“外壳”?只是简单的cmd 或其他什么?我真的怀疑,这是一个时髦的问题
  • 要向某人发表评论,以便他们得到通知,请在他们的名字前加上@。
  • 我会删除 java 标签,添加 windows-oid 标签,看看这是否会在 SO 上的 windows 人群中引起注意。

标签: windows command-line groovy ampersand windows-console


【解决方案1】:

在 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" 被“转义”到-qa&b-q,导致脚本内部有两个命令,产生

'b-q' is not recognized as an internal or external command,
operable program or batch file.

并在“unescaping”时导致无限循环。

在运行 groovy 脚本之前,您可以使用 set DEBUG=true 查看它。

在一堆 hack 中添加另一个 hack,您也可以在startGroovy.bat 中以类似的方式escape &,如下所示:

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 7 x64)中,groovy test.groovy "a&b" 只是挂起......
  • 让我更深入地了解它。看来我在转义 & 时是错误的。我会尝试更多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 2012-02-25
  • 2014-08-03
  • 2014-09-06
  • 2013-04-01
  • 2016-07-08
相关资源
最近更新 更多