Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: using ampersand in command line parameter

Here is the groovy script:

param = args[0]
println(param)

Here is how I run it (Windows 7):

groovy test.groovy a&b

I expect this script prints a&b, but instead get 'b' is not recognized as an internal or external command, operable program or batch file.

I tried to put the argument (a&b in my case) in quotes but it doesn't help. With double quotes, the script hangs. With single quotes I get the same error like without any quotes.

Question: is it possible to take a string with ampersand as command line argument for groovy script?

like image 353
Racoon Avatar asked Nov 05 '14 17:11

Racoon


1 Answers

When executing groovy on Windows, we actually execute %GROOVY_HOME\groovy.bat and then (from groovy.bat):

"%DIRNAME%\startGroovy.bat" "%DIRNAME%" groovy.ui.GroovyMain %*

If we look inside startGroovy.bat, we can see a really ugly hack to deal with arguments (excerpt below):

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%

Therefore, inside startyGroovy.bat "a&b" is "escaped" to -qa&b-q, resulting in two commands inside the script, yielding

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

and causing an infinite loop while "unescaping".

You can see it with set DEBUG=true before running your groovy script.

Adding another hack to the bunch of hacks, you can escape also & in a similar way in startGroovy.bat as follows:

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%

and 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=-%

So that:

groovy test.groovy "a&b"
a&b

Not sure if a clearer/more elegant solution is even posible in Windows.

You can see a similar case with groovy -e "println 2**3" that yields 8 in UNIX console but hangs (infinite loop) in windows.

like image 89
jalopaba Avatar answered Sep 19 '22 00:09

jalopaba