我试图写一个脚本,帮助我在日志中搜索一个短语“已开始”。
到目前为止,我的脚本如下所示:
#!/bin/bash
greperg=
i=3
echo "Web server is going to be polled"
while
i=`expr $i - 1`
#polling
echo "Polling Nr. $i"
grep -q '^started$' log
greperg=$?
#test, if it goes on
test "$greperg" -gt 0 -a "$i" -gt 0
do
#waiting
echo 'waiting ...'
sleep 1
done
if test "$greperg" -eq 0
then
echo "Web server has started"
else
echo -n "Web server is not started"
fi
valid=''
while ((!valid)); do
echo - "Do you want to poll again? (J/N)"
read -t 5 answer
case "$answer" in
[Jj]) result=1; valid=1;;
[Nn]) result=0; valid=1;;
"") result=0; valid=1;;
*) valid=0 ;;
esac
done
echo
if ((result));then
: # ...............(repeat the process again, if its not found ask max 5 times)
else
echo "Timeout"
fi
exit 0在第38行,我不知道怎么重新运行它,有人能帮忙吗?
我要找的是:
投票..。Web服务器尚未启动。等等..。投票..。Web服务器尚未启动。等等..。投票..。Web服务器尚未启动。是否应该再次投票(Y / N)?_Y投票.Web服务器尚未启动。等等..。投票..。Web服务器尚未启动。等等..。投票..。Web服务器尚未启动。如果按要求再次轮询(Y / N)?_N,则不再进行任何尝试。底线: web服务器尚未启动。
发布于 2021-12-22 11:22:05
你的代码有几个奇怪的设计。Bash通常根本不需要使用expr ( shell有内置的整数算法和子字符串匹配工具),您通常希望避免使用explicitly testing $?。我会把它分解成函数来“分而治之”问题空间。
#!/bin/bash
# Print diagnostics to standard error; include script name
echo "$0: Web server is going to be polled" >&2
status=2
poll () {
local i
for ((i=1; i<=$1; ++i)); do
# Move wait to beginning of loop
if (($i > 1)); then
echo "$0: waiting ..." >&2
sleep 1
fi
echo "$0: Polling Nr. $i" >&2
# Just check
if grep -q '^started$' log; then
# return success
return 0
fi
done
# If we fall through to here, return failure
return 1
}
again () {
while true; do
# Notice read -p for prompt
read -t 5 -p "Do you want to poll again? (J/N)" answer
case "$answer" in
[Jj]*) return 0;;
"") continue;;
*) return 1;;
esac
done
}
while true; do
if poll 3
then
echo "$0: Web server has started" >&2
status=0
else
echo "$0: Web server is not started" >&2
status=1
fi
again || break
done
# Actually return the status to the caller
exit "$status"如果希望限制用户重新启动轮询的次数,主脚本中的while true循环可以很容易地调整为for循环,就像poll函数中的那样。我想展示两种不同的设计,只是为了展示给你的选择。
在实际脚本中,我可能会用if速记替换几个简单的this || that测试。总之,
this && that || other大致相当于
if this; then
that
else
other
fi与之不同的是,如果that失败,您还将触发速记情况下的other。
也许还请注意,Bash中的((...))是一个算术上下文。三位for循环也是一个Bash扩展。
https://stackoverflow.com/questions/70288385
复制相似问题