Groovy: using ampersand in command line option

Here is the groovy script:

param = args[0] println(param) 

This is how I run it (Windows 7):

 groovy test.groovy a&b 

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

I tried putting the argument (a & b in my case) in quotation marks, but that won't help. With double quotes, the script freezes. With single quotes, I get the same error as without quotes.

Question: can I take a string with an ampersand as a command line argument for a groovy script?

+6
source share
1 answer

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 will see a really ugly hack of 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" "escaped" to -qa&b-q , which leads to two commands inside the script, which gives

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

and causes an infinite loop during "unescaping".

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

By adding another hack to the bunch of hacks, you can also escape & 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, to:

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

Not sure if a sharper / more elegant solution is even possible on Windows.

You can see a similar case with groovy -e "println 2**3" , which gives 8 in the UNIX console, but hangs (an infinite loop) in windows.

+5
source

Source: https://habr.com/ru/post/977776/


All Articles