简体   繁体   English

docker exec命令的结果

[英]The result of docker exec command

I need to know in my shell script the output of some docker exec commands, for example I have an nginx container and in my script I run: 我需要在我的shell脚本中知道一些docker exec命令的输出,例如我有一个nginx容器,在我的脚本中运行:

docker exec -it containerName /etc/init.d/nginx configtest

I want to continue script execution only if nginx config test is success, not when fail. 我想仅在nginx配置测试成功时才继续执行脚本,而不是在失败时。

I've tried out to use $? 我试过用$? , but it is 0 even then configtest output is fail (because docker exec is successfully executed, as I understand). ,但它是0即使然后configtest输出失败(因为我理解,因为docker exec成功执行)。

Translating my comment into an answer. 将我的评论翻译成答案。 This should work: 这应该工作:

docker exec -it mynginx /etc/init.d/nginx configtest && echo "pass" || echo "fail"

It works for me. 这个对我有用。

我发现这个工作得很好:

docker exec -t -i my-container sh -c 'my-command; exit $?'

The api/client/exec.go#L97-L100 does get the exit code: api/client/exec.go#L97-L100确实得到退出代码:

var status int
if _, status, err = getExecExitCode(cli, execID); err != nil {
    return err
}

That comes from api/client/utils.go#L84-L97 它来自api/client/utils.go#L84-L97

// getExecExitCode perform an inspect on the exec command. It returns
// the running state and the exit code.
func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
    resp, err := cli.client.ContainerExecInspect(execID)
    if err != nil {
        // If we can't connect, then the daemon probably died.
        if err != lib.ErrConnectionFailed {
            return false, -1, err
        }
        return false, -1, nil
    }

    return resp.Running, resp.ExitCode, nil
}

So if your command fail, you will get the exit code. 因此,如果您的命令失败,您将获得退出代码。
Although, as mentioned here, you could use nginx -t instead of configtest . 虽然, 如此处所述,您可以使用nginx -t而不是configtest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM