如何在 bash 中创建一个等待网络服务器响应的循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11904772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a loop in bash that is waiting for a webserver to respond?
提问by sorin
How to create a loop in bash that is waiting for a webserver to respond?
如何在 bash 中创建一个等待网络服务器响应的循环?
It should print a "." every 10 seconds or so, and wait until the server starts to respond.
它应该打印一个“。” 每 10 秒左右,等待服务器开始响应。
Update, this code tests if I get a good response from the server.
更新,此代码测试我是否从服务器获得了良好的响应。
if curl --output /dev/null --silent --head --fail "$url"; then echo "URL exists: $url" else echo "URL does not exist: $url" fi
回答by Thomas Ferris Nicolaisen
Combining the question with chepner's answer, this worked for me:
将问题与 chepner 的回答结合起来,这对我有用:
until $(curl --output /dev/null --silent --head --fail http://myhost:myport); do
printf '.'
sleep 5
done
回答by illagrenan
I wanted to limit the maximum number of attempts. Based on Thomas's accepted answer I made this:
我想限制最大尝试次数。基于托马斯接受的答案,我做了这个:
attempt_counter=0
max_attempts=5
until $(curl --output /dev/null --silent --head --fail http://myhost:myport); do
if [ ${attempt_counter} -eq ${max_attempts} ];then
echo "Max attempts reached"
exit 1
fi
printf '.'
attempt_counter=$(($attempt_counter+1))
sleep 5
done
回答by Bruce Edge
httping is nice for this. simple, clean, quiet.
httping 对此很好。简单,干净,安静。
while ! httping -qc1 http://myhost:myport ; do sleep 1 ; done
while/until etc is a personal pref.
while/until 等是个人偏好。
回答by Serge Stroobandt
回答by BoeroBoy
Interesting puzzle. If you have no access or async api with your client, you can try grepping your tcp sockets like this:
有趣的谜题。如果您的客户端没有访问权限或异步 api,您可以尝试像这样 grepping tcp 套接字:
until grep '***IPV4 ADDRESS OF SERVER IN REVERSE HEX***' /proc/net/tcp
do
printf '.'
sleep 1
done
But that's a busy wait with 1 sec intervals. You probably want more resolution than that. Also this is global. If another connection is made to that server, your results are invalid.
但这是一个繁忙的等待,间隔为 1 秒。您可能想要比这更高的分辨率。这也是全球性的。如果与该服务器建立了另一个连接,则结果无效。
回答by Clot
if you need check if the server is available, cause is restarting or something else, you could try to make an wget to the server and parse the response or the error, if you get a 200 or even a 404 the server is up, you could change the wget timeout with --timeout=seconds, You could set timeout to 10 second and make a loop until the grep over the response have a result.
如果您需要检查服务器是否可用,原因是重新启动或其他原因,您可以尝试对服务器进行 wget 并解析响应或错误,如果您收到 200 甚至 404 服务器已启动,您可以使用 --timeout=seconds 更改 wget 超时,您可以将超时设置为 10 秒并进行循环,直到响应的 grep 产生结果。
i dont know if this is what you are searching or really you need the bash code.
我不知道这是否是您正在搜索的内容,还是您真的需要 bash 代码。