bash docker exec 命令的结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34447818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:03:20  来源:igfitidea点击:

The result of docker exec command

bashshelldocker

提问by Aliance

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

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 0even then configtest output is fail (because docker exec is successfully executed, as I understand).

我试过使用$?,但0即使这样 configtest 输出失败(因为 docker exec 已成功执行,据我所知)。

回答by conradkleinespel

I found thisto be working quite well:

我发现工作得很好:

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

回答by anubhava

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.

这个对我有用。

回答by VonC

The api/client/exec.go#L97-L100does 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 -tinstead of configtest.

因此,如果您的命令失败,您将获得退出代码。
虽然,正如这里提到的,您可以使用nginx -t代替configtest.