我正在编写一些 shell 脚本,其中经常会将一些内容写入文件,然后执行一个读取该文件的应用程序。我发现在我们公司中,网络延迟差异很大,所以简单的 sleep 2
等待时间可能不够稳健。
我尝试编写了一个(可配置的)超时循环,如下:
waitLoop()
{
local timeout=$1
local test="$2"
if ! $test
then
local counter=0
while ! $test && [ $counter -lt $timeout ]
do
sleep 1
((counter++))
done
if ! $test
then
exit 1
fi
fi
}
这对于
test="[ -e $somefilename ]"
有效。但是,仅测试文件是否存在是不够的,有时我需要测试某个字符串是否写入了该文件。我尝试过test="grep -sq \"^sometext$\" $somefilename"
,但这没有起作用。有人可以告诉我原因吗?还有其他更简洁的选项来执行这样的测试吗?