温馨提示:本文翻译自stackoverflow.com,查看原文请点击:bash - how to wait for "docker exec " to complete before continue in shell script
bash docker shell

bash - 如何在外壳程序脚本中继续之前等待“ docker exec”完成

发布于 2020-03-27 11:20:45

我有一个docker exec命令,在继续执行其余的Shell脚本之前,我想等待它完成,我该如何完成?

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

wait
echo done

更新:不应使用-it选项

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

wait
echo done

查看更多

查看更多

提问者
smallbee
被浏览
295
BMitch 2019-07-03 23:19

docker exec命令将等待,直到默认情况下完成为止。docker exec我可以想到的是,在命令运行完成之前返回的可能原因是:

  1. 您已明确要求docker exec使用分离标志aka在后台运行-d
  2. 您正在容器中执行的命令在其运行的进程完成(例如启动后台守护程序)之前返回。在这种情况下,您需要调整正在运行的命令。

这里有些例子:

$ # 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