Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior of windows CMD when running groovy

I have a groovy script that renames files that match a regex I launch it this way

C:\>groovy rename test.* test.txt

It works fine.

But when I try to pass this regex:

C:\>groovy rename test\.(.*) $1_TEST_$1

the command line returns a message:

The syntax of the command is incorrect

and it's not my script - its cmd that writes this. My script never even runs. It also happens even when I wrap the arguments (regex) in quotes.

Q: Why? How can I pass any regex as param?


Since nobody can figure out what's going on, I've made an even simpler example:

test.groovy

println args[0]

I run it: groovy test Bob and the output is, not suprisingly, Bob. But when I run e.g. groovy test .* I get The syntax of the command is incorrect. When I run it groovy test * then a name of a pdf file comes out (that happens to be in the same dir as test.groovy)

like image 886
Queequeg Avatar asked Oct 06 '22 10:10

Queequeg


1 Answers

OK, this appears to be a bug in the startgroovy.bat batch file. The error occurs here:

rem remove the leading space we'll add the first time
if "x%_ARG:~0,1%" == "x " set _ARG=%_ARG:~1%

But the problem is a few lines previously:

rem remove quotes around first arg
for %%i in (%1) do set _ARG=%_ARG% %%~i

This doesn't work as intended if the argument contains wildcards. Certain cases (including a single asterisk) are worked around earlier in the script and others sort of work because the wildcard matches successfully; in this case you don't get an error but the matching file is passed to the Groovy script rather than the wildcard. There are also cases where the wildcard would match but doesn't because the workaround has mangled it.

As near as I can figure, the intent is to not process wildcards, so the fix is straightforward:

rem remove quotes around first arg
for /F %%i in (%1) do set _ARG=%_ARG% %%~i

Now it works for me:

H:\>groovy test .*
.*

I was intending to submit a bug report, but it looks as if I can't do so without first registering with the project web site, so you can submit one if you like.

Side note:

Although the problem is caused by the bug in startgroovy.bat it also exposes a bug (or, at least, an odd behaviour) in the Windows batch processor; environment variable substring expansion behaves oddly if the variable doesn't exist. The if line shown above works as expected (no environment variable substitution) on the command line, but in a batch file it gets mangled, coming out as:

if "x~0,1_ARG:~1

Hence the syntax error.

like image 153
Harry Johnston Avatar answered Oct 10 '22 01:10

Harry Johnston