gpt4 book ai didi

linux - Shell脚本+时间依赖

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:31 25 4
gpt4 key购买 nike

我想为以下内容编写一个 shell 脚本:我想检查服务是否正在运行,如果正在运行则退出 1,否则在 5 分钟未运行后退出 -1。像这样的东西:

while(for 5 minutes) {
if service running, exit 1
}
exit -1 //service is not running even after 5 minutes, so exit -1.

我可以检查服务是否正在运行的情况,但无法添加时间限制部分。

这是我的尝试

if (( $(ps -ef | grep -v grep | grep tomcat7 | wc -l) > 0 )); 
then
echo "running"
else
echo "NOT running"
fi

最佳答案

你应该使用bash sleep命令。 man 页面的摘录:-

您可以在脚本中提供 sleep 5m 以等待 5 分钟并执行操作。

NAME
sleep - delay for a specified amount of time

DESCRIPTION
Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an
integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.

您的解决方案的正确方法是:-

#!/bin/bash
maxAttempts=0
maxCounter=2 # Number of attempts can be controlled by this variable

while [ "$maxAttempts" -lt "$maxCounter" ]; do
if ps -ef | grep -v grep | grep "tomcat7" > /dev/null
then
echo "tomcat7 service running, "
exit 1
else
maxAttempts=$((maxAttempts+1))
sleep 5m # The script waits for 5 minutes before exiting with error code '-1'
fi
done

exit -1

if 条件在 ps -ef | grep -v grep | grep "tomcat7" 返回条件通过的命令成功错误代码。 >/dev/null 将所有标准 outpur(stdout, stderr) 抑制到 /dev/null 以便我们只能使用提供的命令的退出代码。

关于linux - Shell脚本+时间依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37987619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com