执行 shell 脚本并将其输出用作下一个 gradle 任务的输入

executing shell script and using its output as input to next gradle task

我正在使用 gradle 进行构建和发布,所以我的 gradle 脚本执行 shell 脚本。 shell 脚本输出一个 ip 地址,必须将其作为输入提供给我的下一个 gradle ssh 任务。我能够获取输出并在控制台上打印,但无法将此输出用作下一个任务的输入。

remotes {
  web01 {
    def ip = exec {
    commandLine './returnid.sh'
    }
    println ip  --> i am able to see the ip address on console
    role 'webServers'
    host = ip  --> i tried referring as $ip '$ip' , both results into syntax error
    user = 'ubuntu'
    password = 'ubuntu'
  }
}

task checkWebServers1 << {

  ssh.run {
    session(remotes.web01) {
    execute 'mkdir -p /home/ubuntu/abc3'
}
}
}

但它会导致错误“

What went wrong:
Execution failed for task ':checkWebServers1'.
 java.net.UnknownHostException: {exitValue=0, failure=null}"

任何人都可以帮助我以正确的语法使用输出变量或提供一些可以帮助我的提示。

提前致谢

它不起作用的原因是 exec 调用 return 是 ExecResult(这里是 JavaDoc description)并且它不是执行。

如果您需要获取文本输出,那么您必须指定 exec 任务的 standardOutput 属性。可以这样做:

remotes {
    web01 {
        def ip = new ByteArrayOutputStream()
        exec {
            commandLine './returnid.sh'
            standardOutput = ip
        }
        println ip
        role 'webServers'
        host = ip.toString().split("\n")[2].trim()
        user = 'ubuntu'
        password = 'ubuntu'
    }
}

请注意,默认情况下 ip 值会有多行输出,包括命令本身,因此必须对其进行解析以获得正确的输出,对于我的 Win 机器,这可以这样完成:

ip.toString().split("\n")[2].trim()

这里只需要输出的第一行。