In my gradle file I defined the following task:
task text_example <<
{
//?!? commandLine ''
println 'Fam Flinstone'
}
I want to put inside this task some commands line. How can I do that ?
I'm using a library to automatically publish in google play. My project is based on Product Flavors and I need to pass in terminal command line by command line for every and each one of my flavors. So I want to pass all commands line in test_example
task.
You basically have two major convenient options:
Use Gradle Exec task type
task fooExec(type: Exec) {
workingDir "${buildDir}/foo"
commandLine 'echo', 'Hello world!'
doLast {
println "Executed!"
}
}
Use Gradle Project.exec method
task execFoo {
doLast {
exec {
workingDir "${buildDir}/foo"
executable 'echo'
args 'Hello world!'
}
println "Executed!"
}
}
In both cases inside the closure you can specify execution parameters using methods of ExecSpec. Standard output and error output from the executed commands will be redirected to stdout and stderr of the gradle process.
There's an important caveat mentioned in the comments below: Gradle's exec
does not evaluate a command line like a shell (e.g. Bash on Linux or CMD on Windows) would, it simply executes specified executable with the provided arguments.
This has some hidden consequences that one needs to keep in mind:
To execute a 'command', one needs to specify a valid existing executable file.
The most common case when this comes up is when trying to use 'commands' that are implemented on a specific OS by a shell and do not have an available implementation in a form of an executable file (e.g. echo
and similar commands on Windows).
There are no 'fancy' features supported by modern shells like streams redirects and similar (although you can still redirect stdout of one process to stdin of another using two separate exec
invocations with custom IO configuration).
User-defined aliases (e.g. defined in ~/.bsahrc
) are not available.
The 'common' work around to 'easily' get a modern shell's functionality inside Gradle would be to actually run a shell process and provide the command line as its argument, e.g. if using Bash:
task shellExec(type: Exec) {
workingDir "${buildDir}/foo"
commandLine 'bash', '-c', "echo 'Hello world!'"
}
However, this approach instantly binds the build script to a particular platform making it inoperable on platforms that do not have that particular shell (e.g. above example would not work on Windows).