【问题标题】:How do I execute shell script from Jenkins groovy script in the parameters option?如何在参数选项中从 Jenkins groovy 脚本执行 shell 脚本?
【发布时间】:2015-07-27 00:49:56
【问题描述】:

我想在 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

【问题讨论】:

  • 什么不起作用?痕迹,错误,...?
  • 尝试sh echo "hello world" > test 或更好的echo "hello world" > /tmp/test,以防万一它正常工作但您找不到文件。
  • 谢谢波西米亚人。但它也不起作用。
  • 确保在正确的位置搜索文件。尝试使用绝对路径并检查 Jenkins 主文件系统。在 Jenkins 中,groovy 通常在 master 上执行。

标签: shell groovy jenkins


【解决方案1】:

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

使用上面的 shell 脚本运行 groovy 将在 groovy 脚本的标准输出上产生输出 Test redirect

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

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

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

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

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多