如何执行等待上一个脚本先完成的下一个脚本?

时间:2021-07-17 12:51:34

标签: bash shell script

https://squidfunk.github.io/mkdocs-material/creating-your-site/#previewing-as-you-write 中,有一个命令可以启动我的文档站点。

docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material

我希望它启动后,我会自动打开浏览器看到它。

我写了一个脚本如下

docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material

open http://localhost:8000

但事实证明无法触发 open 命令,因为前一个 docker run 仍在保持进程。

如果我使用 & 如下,那么 open 会在页面准备好之前被调用得太快

docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material &

open http://localhost:8000

我怎样才能在正确的时间接到 open 的电话?

(仅供参考,我正在使用 GNU bash, version 3.2.57(1)-release

2 个答案:

答案 0 :(得分:2)

<块引用>

我怎样才能在正确的时间被调用?

在恰好正确的时间打开浏览器需要您的服务器 mkdocs 发出一些它已准备就绪的信号。既然你可能不想修改服务器的代码,那么你只需要等待合适的时间,然后打开页面即可。

要么手动测量一次启动时间,然后使用固定的等待时间,要么反复检查页面直到加载完毕。

在这两种情况下,docker 命令和打开页面的过程必须并行运行。 bash 可以使用后台作业 (... &) 并行运行。由于 docker -it 必须在前台运行,因此我们将 open 作为后台作业运行。这可能看起来有点奇怪,因为我们似乎在启动服务器之前打开了网站,但请记住,这两个命令是并行运行的。

要么

# replace 2 with your measured time
sleep 2 && open http://localhost:8000 &
docker run --rm -it -p 8000:8000 -v "${PWD}:/docs" squidfunk/mkdocs-material

while ! curl http://localhost:8000 -s -f -o /dev/null; do
  sleep 0.2
done && open http://localhost:8000 &
docker run --rm -it -p 8000:8000 -v "${PWD}:/docs" squidfunk/mkdocs-material

答案 1 :(得分:0)

听起来(对我来说)像:

  • docker run 是一个阻塞进程(它不会退出和/或将控制权返回给控制台)所以......
  • 永远不会运行 open(除非 docker run 命令被中止,在这种情况下 open 将失败),并且 ...
  • docker run 推入后台意味着 open 在 URL 完全可用之前运行

如果是这种情况,我想知道您是否可以执行以下操作:

docker run ... &                          # put in background, return control to console
sleep 3                                   # sleep 3 seconds
open ...

注意:手动选择休眠秒数(在本例中为 3)并不理想,但可以保证 URL 可用性不会让你悬着应该可以通过一些测试

另一个“基本”选项可能是与 sleep 组合的循环结构,例如:

docker run ... &
while true                        # loop indefinitely
do
    sleep 1                       # sleep 1 sec
    open ...  2>/dev/null         # try the open
    [[ $? == 0 ]] && break        # if it doesn't fail then break out of loop, ie, 
                                  # if it does fail then repeat loop
done