在Jenkins管道外壳中运行嵌套命令 [英] Running nested commands in Jenkins pipeline 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" requires at least 1 argument(s).
我试图在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("\n", " ")
这篇关于在Jenkins管道外壳中运行嵌套命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!