首页 文章

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

提问于
浏览
6

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

截至目前,我能够调用shell脚本并捕获一些文件,但我无法创建新文件或从中调用另一个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

1 回答

  • 13

    由于您是从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
    

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

    #!/bin/bash
    echo "Test redirect"
    

    使用上面的shell脚本运行groovy将在groovy脚本的stdout上生成输出 Test redirect

    现在在script.sh中添加exec` 的stdout重定向:

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

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

    您可以在bash中阅读有关I / O重定向的更多信息here

相关问题