如何在参数选项中从 Jenkins groovy 脚本执行 shell 脚本?

How do I execute shell script from Jenkins groovy script in the parameters option?

我想在 Uno-Choice 动态引用参数中调用一个 shell 脚本 并执行一些操作(创建一些文件并调用其他一些 shell 来自被调用的 shell 脚本的脚本).

截至目前,我可以调用 shell 脚本和 cat 一些文件,但我不能 创建新文件或从中调用另一个 shell 脚本。

def sout = new StringBuffer(), serr = new StringBuffer()

// 1) 
def proc ='cat /home/path/to/file'.execute()
//display contents of file

// 2) 
def proc="sh /home/path/to/shell/script.sh".execute()
//to call a shell script but the above dosent work if I echo some contents
//into some file.

proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
return sout.tokenize()

例如:- 在 script.sh 中,如果我添加行

echo "hello world" > test

然后没有创建测试文件

更多理解:

Groovy executing shell commands

http://jenkins-ci.361315.n4.nabble.com/Executing-a-shell-python-command-in-Jenkins-Dynamic-Choice-Parameter-Plugin-td4711174.html

由于您是 运行 来自 groovy 包装器的 bash 脚本,stdout 和 stderr 已经被重定向到 groovy 包装器。为了覆盖它,您需要在 shell 脚本中使用 exec

例如:

groovy脚本:

def sout = new StringBuffer(), serr = new StringBuffer()

def proc ='./script.sh'.execute()

proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout

名为 script.sh 的 shell 脚本位于同一文件夹中:

#!/bin/bash
echo "Test redirect"

运行 groovy 和上面的 shell 脚本将在 groovy 脚本

的标准输出上产生输出 Test redirect

现在在 script.sh` 中使用 exec 添加标准输出重定向:

#!/bin/bash
exec 1>/tmp/test
echo "Test redirect"

现在 运行 groovy 脚本将创建一个文件 /tmp/test,其内容为 Test redirect

您可以在 bash here

中阅读有关 I/O 重定向的更多信息