我正在编写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
}
Run Code Online (Sandbox Code Playgroud)
这适用于test="[ -e $somefilename ]".但是,测试存在是不够的,我有时需要测试某个字符串是否写入文件.我试过了
test="grep -sq \"^sometext$\" $somefilename",但这没用.有人可以告诉我为什么吗?
是否有其他更简洁的选项来执行此类测试?
您可以这样设置测试变量:
test=$(grep -sq "^sometext$" $somefilename)
Run Code Online (Sandbox Code Playgroud)
你不工作的原因grep是引号真的很难在参数中传递。您需要使用eval:
if ! eval $test
Run Code Online (Sandbox Code Playgroud)