如何在shell中等待文件创建并监听其内容直到超时

问题描述 投票:0回答:1

我正在尝试在docker中运行一个程序,一旦程序成功启动,它就会在docker的文件系统中创建一个FIFO文件,并在其中写入一个“成功”字符串。我知道,如果文件存在,我可以通过

tail -f
流式传输文件内容,但这将始终等到我在 cli 上点击
ctrl-c
。另外,如果文件尚未创建,如何扩展这种情况?

我想知道是否有一个shell命令可以等待直到文件被写入非空字符串,并且当我开始等待时这个文件可能不存在。一旦达到超时,等待就会退出。

请注意,此命令将通过

docker exec -i myContainer the_desired_command...
传递给 docker。

bash docker shell
1个回答
5
投票

如果文件不存在,则大多数尝试读取其内容的命令都会失败。

要克服这个问题,您可以使用带有

until
sleep
循环:

#!/bin/bash

file=/file/to/check

until [ -s "$file" ]; do sleep 1; done

# Now we can really start the operations
# ...

此代码将每 1 秒测试一次文件是否存在和非空。当循环存在时,您将确保文件存在并且非空。


这里有一个添加超时的方法:

#!/bin/bash

file=/file/to/check
timeout=30  # seconds to wait for timeout
SECONDS=0   # initialize bash's builtin counter 

until [ -s "$file" ] || (( SECONDS >= timeout )); do sleep 1; done

[ -s "$file" ] || exit 1 # timed-out

# start the operations
# ...
© www.soinside.com 2019 - 2024. All rights reserved.