georgiana_e
georgiana_e

Reputation: 1869

execute bash command in a gradle function

I want to create a generic function in gradle that executes a command. This function is called from a task.

The function executeCommand is triggered from the task copyFile but it seems that the commandLine commands are not executed. I did this because I need a generic ececuteCommand functionality that is triggered from multiple jobs.

def executeCommand(execCmd) {
        try {
           exec {
                        println("execute $execCmd in .")
                        commandLine 'bash', '-c',  "ls -la"
                        commandLine 'bash', '-c',  "${execCmd}"
            }
        }
        catch(Exception e){
            println("Exception: $e")
        }
}

task copyFile {
    doLast {
        if(project.hasProperty('file')) {
            ext.myFile = file
            def execCmd="cp ${myFile} ."
            executeCommand(${execCmd})
        }
        else {
            println("Please specifiy argument files -Pfile=SRC_PATH")
        }
    }
}

Upvotes: 0

Views: 3494

Answers (1)

M.Ricciuti
M.Ricciuti

Reputation: 12096

There is a syntax error in your script, you should normally have an error as follows during execution:

* What went wrong:
Execution failed for task ':copyFile'.
> Could not find method $() for arguments [build_djiuilz6w3giaud8hgmf0oze7$_run_closure2$_closure5$_closure6@57fdda61] on task ':copyFile' of type org.gradle.api.DefaultTask. (normally you should have an error when trying to execute it : **

you need to replace the following statement in your copyFile.doLast{ } block:

executeCommand(${execCmd})

with:

executeCommand( execCmd)
// or:  executeCommand( "${execCmd}" )

NOTE: in the exec {} block of your executeCommand function, there are two calls to commandLine function: only the second one will have effect so the command 'ls -al' will never be executed.

The rest of your script seems valid and should work as expected.

Upvotes: 1

Related Questions