在 Jenkins 管道 shell 中运行嵌套命令 [英] Running nested commands in Jenkins pipeline shell

查看:32
本文介绍了在 Jenkins 管道 shell 中运行嵌套命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Jenkins 管道中运行嵌套的 shell 命令,例如:

I want to run nested shell command for example like this in Jenkins pipeline:

docker stop $(docker ps -aq)

不幸的是,当我将其格式化为管道语法时:

Unfortunately when I format it into pipeline syntax:

sh('docker stop $(docker ps -aq)')

Jenkins 似乎没有正确运行它们,但输出:

Jenkins does not seem to run them correctly, but outputs that:

docker stop"至少需要 1 个参数.

我尝试在 bash 下运行命令,如下所示:在 jenkins 管道上运行 bash 命令但最终会遇到类似的问题.任何想法如何解决这个问题?

I tried to run the command under bash like told here: Run bash command on jenkins pipeline But end up with similar issue. Any ideas how to solve this?

推荐答案

如果将 shell 命令扩展为两行,这对于 Jenkins Pipeline 来说会变得更容易:

This becomes easier for Jenkins Pipeline if you expand the shell command into two lines:

  • 第一个捕获要停止的 Docker 容器.
  • 第二个停止在第一个命令中捕获的那些 Docker 容器.

我们使用第一行将shell命令的输出捕获到一个变量中:

We use the first line to capture the output of the shell command into a variable:

containers = sh(returnStdout: true, script: 'sudo/usr/bin/docker ps -aq')

然后我们使用第二个命令对存储在变量中的第一个命令的捕获输出进行操作:

We then use the second command to operate on the captured output from the first command stored in a variable:

sh("sudo/usr/bin/docker stop $containers")

请注意,docker 命令通常对 docker ps -aq 的输出感到满意,以便与其他命令一起操作,但如果它不喜欢存储在变量,你可以像下面这样重新格式化它:

Note that the docker command is normally comfortable with the output of docker ps -aq for operating on with its other commands, but if it dislikes the output stored in the variable, you can reformat it like the following:

containers = sh(returnStdout: true, script: 'sudo/usr/bin/docker ps -aq').trim()

例如,这将去除前导空格和尾随换行符.Docker CLI 通常不关心这一点,但这里可能需要进行一些重新格式化.

This would, for example, strip the leading whitespace and trailing newlines. The Docker CLI normally does not care about that, but some reformatting may prove necessary here.

由于在此处删除换行符会导致组合容器 ID 很长,因此我们需要(如您所述)将其替换为空格以分隔容器 ID.这将使存储在 containers 变量中的字符串格式化:

Since removing the newlines here would result in a long combined container ID, we need to (as you noted) replace it with a whitespace to delimit the container IDs. That would make the formatting for the string stored in the containers variable:

containers = sh(returnStdout: true, script: 'sudo/usr/bin/docker ps -aq').replaceAll(" ", " ")

containers = sh(returnStdout: true, script: 'sudo /usr/bin/docker ps -aq').replaceAll(" ", " ")

这篇关于在 Jenkins 管道 shell 中运行嵌套命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆