Executing commands with Gradle?

前端 未结 2 465
后悔当初
后悔当初 2021-02-13 02:41

I am trying to execute a command with gradle with the below task:

task stopServer(dependsOn: war, type: Exec) << {
    commandLine \'pkill -9 tomcat\'
}
         


        
2条回答
  •  别那么骄傲
    2021-02-13 03:39

    I believe you're looking for this:

    task stopServer(dependsOn: war, type: Exec) {
         commandLine "pkill", " -9", "tomcat"
    }
    

    The main difference is very subtle - I just deleted two characters. The << is gone from the task definition. The other difference is that the commandLine expects the executable to be passed in separately from the arguments to it.

    I removed the << because of an important idea in gradle: the build lifecycle. There's configuration and execution phases (that's not all, but it's enough to explain this).

    The << is like saying doLast - it adds the closure you pass to the end of the actions (the execution phase) for this task. So that means here, it's going to try and execute the command like normal (it's an Exec object, after all), and only then, once it's executed, will it call your block - the block setting commandLine. So when it's executing, execCommand really is null, and would be until your block was run. This is the heart of your problem.

    Without the << (also known as left-shift), that same block runs during the configuration phase. So the exec command gets set before it runs, and it works.

提交回复
热议问题