Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Gradle, how can I ensure that a command exists

Tags:

I am using Gradle for AOSP, I would like to check if a command exists in my build environment.

task printCommand{
    doLast{
        def command = "git --version"
        println command.execute().text
    }
}

Above code run perfect, it will print the output from command "git --version".

But I try another command according to Check if a program exists from a Bash script

task printCommand{
    doLast{
        def command = "command -v docker"
        println command.execute().text
    }
}

It always show the wrong message like this.

Execution failed for task ':printCommand'. java.io.IOException: Cannot run program "command": error=2, No such file or directory

Why I can't use "command -v docker" in this way ?

Are there any better ways to check if a command exists in Gradle ?

like image 574
Corey Avatar asked Sep 28 '17 05:09

Corey


2 Answers

command is a builtin bash command, not a binary.

groovy's String.execute will start a process. The binary that the process is started from has to be given fully qualified (e.g. "/usr/bin/docker --version") or must be found on your $PATH (or %PATH%)

like image 56
Frank Neblung Avatar answered Oct 11 '22 14:10

Frank Neblung


Get back to the subject, I find the way to ensure that a command exists while using Gradle, this code can avoid Gradle script terminated by non-zero exitValue, and print the appropriate information.

task checkCommand{
    doLast{
        result = exec{
            def command = "command -v docker"
            ignoreExitValue = true
            executable "bash" args "-l", "-c", command
        }
        if(result.getExitValue()==0){
            println "Has Docker"
        }else{
            print "No Docker"
        }
    }
}

Update 2019/02/23

If you get this error:

Could not set unknown property 'result' for task ':checkCommand' of type org.gradle.api.DefaultTask

Add def in front of result will fix this issue.

like image 45
Corey Avatar answered Oct 11 '22 14:10

Corey