我正在尝试在docker中运行一个程序,一旦程序成功启动,它就会在docker的文件系统中创建一个FIFO文件,并在其中写入一个“成功”字符串。我知道如果文件存在,我可以通过 流式传输文件的内容tail -f,但这将始终等到我点击ctrl-ccli。另外,如果文件尚未创建,如何扩展这种情况?
我想知道是否有一个 shell 命令可以等待直到文件被写入非空字符串,并且在我开始 wait 时该文件可能不存在。一旦达到超时,等待就会退出。
请注意,此命令将传递给带有docker exec -i myContainer the_desired_command....
如果该文件不存在,则大多数尝试读取其内容的命令都会失败。
为了克服这个问题,您可以使用until带有以下内容的循环sleep:
#!/bin/bash
file=/file/to/check
until [ -s "$file" ]
do
sleep 1
done
# Now we can really start the operations
# ...
Run Code Online (Sandbox Code Playgroud)
此代码将每 1 秒测试一次文件是否存在和非空。当循环存在时,您将确保文件存在并且非空。
这是添加超时的方法:
#!/bin/bash
file=/file/to/check
timeout=30 # seconds to wait for timeout
SECONDS=0 # initialize the bultin counter
until [ -s "$file" ] || (( SECONDS >= timeout ))
do
SECONDS=$((SECONDS+1))
sleep 1
done
[ -s "$file" ] || exit 1 # timed-out
# start the operations
# ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1471 次 |
| 最近记录: |