如果命令采用不同的形式,是否有办法在Windows和Mac上执行任务?例如:
task stopTomcat(type:Exec) {
// use this command line if on Windows
commandLine 'cmd', '/c', 'stop.cmd'
// use the command line if on Mac
commandLine './stop.sh'
}
你将如何在Gradle中做到这一点?
答案 0 :(得分:37)
您可以根据系统属性的值有条件地设置commandLine
属性。
if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
commandLine 'cmd', '/c', 'stop.cmd'
} else {
commandLine './stop.sh'
}
答案 1 :(得分:2)
如果脚本或可执行文件在Windows和Linux上是相同的,那么您将能够执行以下操作,从而只需调用如下函数即可定义参数一次:
import org.apache.tools.ant.taskdefs.condition.Os
task executeCommand(type: Exec) {
commandLine osAdaptiveCommand('aws', 'ecr', 'get-login', '--no-include-email')
}
private static Iterable<String> osAdaptiveCommand(String... commands) {
def newCommands = []
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
newCommands = ['cmd', '/c']
}
newCommands.addAll(commands)
return newCommands
}