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 ?
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%
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With