2

I have a docker exec command, and I want to wait for it to complete before continuing the rest of a shell script, how do I accomplish that?

#!/bin/bash
docker exec -it debian sleep 10;

wait
echo done

Update: should not use -it option

#!/bin/bash
docker exec debian sleep 10;

wait
echo done
3
  • 1
    That should be the normal shell behavior. Do you have some evidence that it’s not working?
    – David Maze
    Jul 3, 2019 at 14:43
  • 1
    Running docker exec ... sleep 10 against a container I have running on my system definitely takes 10 seconds before it returns.
    – David Maze
    Jul 3, 2019 at 14:53
  • 1
    It's the default behavior. Docker exec waits for the command to complete. Jul 3, 2019 at 14:56

2 Answers 2

4

The docker exec command will wait until it completes by default. The possible reasons for docker exec to return before the command it runs has completed, that I can think of, are:

  1. You explicitly told docker exec to run in the background with the detach flag, aka -d.
  2. The command you are exec'ing inside the container returns before a process it runs has completed, e.g. launching a background daemon. In that scenario, you need to adjust the command you are running.

Here are some examples:

$ # launch a container to test:
$ docker run -d --rm --name test-exec busybox tail -f /dev/null
a218f90f941698960ee5a9750b552dad10359d91ea137868b50b4f762c293bc3

$ # test a sleep command, works as expected
$ time docker exec -it test-exec sleep 10

real    0m10.356s
user    0m0.044s
sys     0m0.040s

$ # test running without -it, still works
$ time docker exec test-exec sleep 10

real    0m10.292s
user    0m0.040s
sys     0m0.040s

$ # test running that command with -d, runs in the background as requested
$ time docker exec -itd test-exec sleep 10 

real    0m0.196s
user    0m0.056s
sys     0m0.024s

$ # run a command inside the container in the background using a shell and &
$ time docker exec -it test-exec /bin/sh -c 'sleep 10 &'

real    0m0.289s
user    0m0.048s
sys     0m0.044s
2

Update: should not use -it option. This should work.

#!/bin/bash
docker exec debian sleep 10;

wait
echo done
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.