How can I provide command line args to application started with 'gradle run'?

Is there a way to execute the ‘run’ task while also specifying command line arguments that get forwarded to the executed java application?

Something like ‘$ gradle run args1 args2’ with args1 and args2 ending up in ‘args[]’ of the main method.

Is it possible at all?

2 Likes

The ‘run’ task is of type JavaExec, which means that it can easily be configured with command line parameters. If you want to set those from the command line, you have to pass system or project properties and configure the ‘run’ task accordingly.

Yes, I checked the JavaExec documentation out already. It would be necessary to set the args list.

I just hoped that there would be some easier, less manual, more “standard” way to pass arguments to the executing java application.

‘gradle run -Parg1=foo -Parg2=bar’ and then manually parsing argx properties into a List feels not very gradle-like, especially if something like this is required in several unrelated projects.

I was aiming to remove the need for a real application distribution by means of zip, using just Gradle instead.

Anyway, I think an example in the documentation of the application plugin concerning command line arguments (and also io redirect as described in http://forums.gradle.org/gradle/topics/how_can_i_execute_a_java_application_that_asks_for_user_input ) would be helpful.

Thanks for the fast answer!

you can write a plugin for that and than reuse it in your different projects. To get started on this, you might have a look on a posting I did some time ago to pass system properties to the test task: http://forums.gradle.org/gradle/topics/passing_system_properties_to_test_task

You might want to make it a single ‘-Pargs=…’ property. Our longer term goal is to have a generic way for setting task properties from the command line.

Anyway, I think an example in the documentation of the application plugin concerning command line arguments (and also io redirect as described in Gradle Forums… ) would be helpful.

Pull requests are very welcome.

Also consider doing something like this:

run {

if ( project.hasProperty(“appArgs”) ) {

args Eval.me(appArgs)

}

}

Then run your application with a little Groovy on the command line like this:

gradle run -PappArgs="[’-u’, ‘myuser’, ‘some other argument’, ‘and/a/path’]"

And if you want to get really spiffy you can use a shell script to invoke gradle like this:

#!/bin/bash

Join arguments in a string. But not quite like you’d expect… see next line.

printf -v var "’%s’, " “$@”

Remove trailing ", "

var=${var%??}

gradle run -PappArgs="[$var]"

Then invoke the shell script by

./run.sh -u myuser “some other argument” and/a/path

And everything is groovy.

2 Likes