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:
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.
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).
I found this to be working quite well:
docker exec -t -i my-container sh -c 'my-command; exit $?'
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.
The api/client/exec.go#L97-L100
does get the exit code:
var status int
if _, status, err = getExecExitCode(cli, execID); err != nil {
return err
}
That comes from 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
.