Search code examples
shelljenkinsjenkins-pipeline

Running nested commands in Jenkins pipeline 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 does not seem to run them correctly, but outputs that:

"docker stop" requires at least 1 argument(s).

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?


Solution

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

    • The first to capture the Docker containers that you want to stop.
    • The second to stop those Docker containers captured in the first command.

    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")

    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()

    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.

    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", " ")