将Docker日志尾部的最后一行存储到Shell变量中

时间:2019-03-25 05:24:36

标签: linux shell docker unix scripting

我正在尝试完成一个相当简单的任务,但是我已经失败了好几个小时了。我确定我缺少一些简单的东西。

我要做的就是将docker log的最后一行捕获到Shell脚本中的变量中。


这是我的设置:

Dockerfile:

FROM python:3.7.2
WORKDIR /workspace
RUN pip install jupyterlab
EXPOSE 8888
ENTRYPOINT ["jupyter", "lab", "--ip=0.0.0.0", "--allow-root", "--no-browser"]

run.sh:

#!/bin/sh

docker build -t ml/jupyterlab .
docker rm -f ml-jupyterlab
docker run -d -p 8888:8888 -v $(pwd)/src:/workspace --name ml-jupyterlab ml/jupyterlab

until [[ "$url_info" =~ "token" ]]; do
    url_info=$(docker logs ml-jupyterlab --tail 1)
    sleep 0.1 
done

echo "$url_info"

如果有帮助,这是来自docker容器的登录信息,我试图捕获http://(6f8bec0aa3d9 or 127.0.0.1):8888/?token=a6001a419b22d60dd3e5215d52794c5be7c0b368664c3505中的最后一行$url_info

[I 05:22:37.925 LabApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
[I 05:22:39.190 LabApp] JupyterLab extension loaded from /usr/local/lib/python3.7/site-packages/jupyterlab
[I 05:22:39.190 LabApp] JupyterLab application directory is /usr/local/share/jupyter/lab
[W 05:22:39.194 LabApp] JupyterLab server extension not enabled, manually loading...
[I 05:22:39.198 LabApp] JupyterLab extension loaded from /usr/local/lib/python3.7/site-packages/jupyterlab
[I 05:22:39.198 LabApp] JupyterLab application directory is /usr/local/share/jupyter/lab
[I 05:22:39.199 LabApp] Serving notebooks from local directory: /workspace
[I 05:22:39.199 LabApp] The Jupyter Notebook is running at:
[I 05:22:39.200 LabApp] http://(6f8bec0aa3d9 or 127.0.0.1):8888/?token=a6001a419b22d60dd3e5215d52794c5be7c0b368664c3505
[I 05:22:39.200 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 05:22:39.204 LabApp]

    To access the notebook, open this file in a browser:
        file:///root/.local/share/jupyter/runtime/nbserver-1-open.html
    Or copy and paste one of these URLs:
        http://(6f8bec0aa3d9 or 127.0.0.1):8888/?token=a6001a419b22d60dd3e5215d52794c5be7c0b368664c3505

执行以下操作

$ chmod +x run.sh
$ ./run.sh

进入无限循环,$url_info仍然null


我非常感谢能在这里获得的任何帮助。

2 个答案:

答案 0 :(得分:1)

最后,我使用以下脚本解决了这个问题:

#!/bin/sh

docker build -t ml/jupyterlab .
docker rm -f ml-jupyterlab
docker run -d -p 8888:8888 -v $(pwd)/src:/workspace --name ml-jupyterlab ml/jupyterlab

until [[ "${url_info}" != "" ]]; do
    docker logs ml-jupyterlab &> logs
    url_info=$(cat logs | grep token | head -1)
    sleep 0.1 
done


echo "$url_info"

答案 1 :(得分:0)

有可能在0.1秒的暂停时间内生成多个日志文件,其中包括一个带有“ token”的日志文件。

这意味着最新行可能包括令牌(该令牌已经存在于日志中,在前几行中)

代替测试
until [[ "${url_info}" != "" ]]; do
    url_info=$(docker logs ml-jupyterlab --tail 100|grep token)
    sleep 0.1 
done

只要url_info为空,请继续进行测试。