Good day. It is necessary to make a decision to run the second command based on the results of the previous one.
I need to check if npm package is installed and if it doesn't exist start installing. npm list -g package
(if the package does not exist, this command will return a value different from 0) and npm install -g package
commands are used for the issue. It is easy to execute the logic in a terminal using ||
operator:
npm list -g package || npm install -g package
Then I created installPackage
task in gradle.build file:
task installPackage(type: Exec) {
commandLine 'npm', 'list', '-g', 'package', '||', 'npm', 'install', '-g', 'package'
}
And none of the commands work. In fact, the result is displayed as if npm list -g
command was used.
Is there a way to do this without using third-party tools or plugins? What options could be used? Thanks a lot
CodePudding user response:
There is a question about execute multiple commands Gradle -- execute multiple commands from task, but it doesn't support &&
or ||
. Just pick from below solutions that make sense to you. Personally I prefer solution 1.
1. Put your command in a script and call the script
- More flexible
- More readable (as you don't need to use ',' to separate the command)
- But need to refer to another file
task installPackageWithScript(type: Exec) {
commandLine('sh', './bin/installPackage.sh')
}
2. Refer to Gradle - How to execute command line in doLast and get exit code?, get the exit code from first command to determine whether second command is needed.
- No need to refer other file
- But less readable and maintainable
task installPackageInline(type: Exec) {
commandLine('npm', 'list', '-g', 'package')
doLast {
if (execResult.exitValue == 0) {
println "list Success"
} else {
println "list Fail, run install"
exec { commandLine('npm', 'install', '-g', 'package') }
}
}
}