如何在 运行 bash 脚本中更改睡眠时间
how can I change SLEEP time in a running bash script
附录:正如 Matthias 所指出的,下面的代码运行良好。错误发生在另一个地方。简而言之:如果您希望在脚本运行时更改 sleep
,例如由于某个事件,您可能会使用下面的代码。
原始描述:
我的 bash 脚本应该检查特定状态 - 例如文件的存在 - 每 5 分钟。如果状态符合预期,则一切正常。但如果状态不是这样,检查应该以较短的频率进行,直到一切恢复正常。
示例:
NORMAL_SLEEP=300
SHORT_SLEEP=30
CUR_SLEEP=''
while :
do
if [ -f /tmp/myfile ]; then
logger "myfile still exists. Next check in 5min"
CUR_SLEEP=$NORMAL_SLEEP
else
logger "myfile disappeared. Check again in 30s!"
CUR_SLEEP=$SHORT_SLEEP
echo "/tmp/myfile was removed. Check this!" \
| mailx -s "alert: myfile missed" johndoe@somewhere.com
fi
trap 'kill $SLEEP_PID; exit 1' 15
sleep $CUR_SLEEP &
SLEEP_PID=$!
wait
done
问题:睡眠时间不适应...
看过 Bash Script: While-Loop Subshell Dilemma 但不幸的是看不出它如何解决我的问题。
代码 运行 在我的机器上没问题。这是我 运行(更改时间值只是为了测试):
./script.sh
--> "myfile disappeared. Check again in 30s!" 每 2 秒打印一次
touch /tmp/myfile
./script.sh
--> "myfile still exists. Next check in 5min" 每 5 秒打印一次
文件,script.sh
:
#!/bin/bash
NORMAL_SLEEP=5
SHORT_SLEEP=2
CUR_SLEEP=''
while :
do
if [ -f /tmp/myfile ]; then
echo "myfile still exists. Next check in 5min"
CUR_SLEEP=$NORMAL_SLEEP
else
echo "myfile disappeared. Check again in 30s!"
CUR_SLEEP=$SHORT_SLEEP
echo "/tmp/myfile was removed. Check this!" \
| mailx -s "alert: myfile missed" johndoe@somewhere.com
fi
trap 'kill $SLEEP_PID; exit 1' 15
sleep $CUR_SLEEP &
SLEEP_PID=$!
wait
done
我可能给 johndoe@somewhere.com
发了一些邮件,但没关系。
附录:正如 Matthias 所指出的,下面的代码运行良好。错误发生在另一个地方。简而言之:如果您希望在脚本运行时更改 sleep
,例如由于某个事件,您可能会使用下面的代码。
原始描述:
我的 bash 脚本应该检查特定状态 - 例如文件的存在 - 每 5 分钟。如果状态符合预期,则一切正常。但如果状态不是这样,检查应该以较短的频率进行,直到一切恢复正常。
示例:
NORMAL_SLEEP=300
SHORT_SLEEP=30
CUR_SLEEP=''
while :
do
if [ -f /tmp/myfile ]; then
logger "myfile still exists. Next check in 5min"
CUR_SLEEP=$NORMAL_SLEEP
else
logger "myfile disappeared. Check again in 30s!"
CUR_SLEEP=$SHORT_SLEEP
echo "/tmp/myfile was removed. Check this!" \
| mailx -s "alert: myfile missed" johndoe@somewhere.com
fi
trap 'kill $SLEEP_PID; exit 1' 15
sleep $CUR_SLEEP &
SLEEP_PID=$!
wait
done
问题:睡眠时间不适应...
看过 Bash Script: While-Loop Subshell Dilemma 但不幸的是看不出它如何解决我的问题。
代码 运行 在我的机器上没问题。这是我 运行(更改时间值只是为了测试):
./script.sh
--> "myfile disappeared. Check again in 30s!" 每 2 秒打印一次touch /tmp/myfile
./script.sh
--> "myfile still exists. Next check in 5min" 每 5 秒打印一次
文件,script.sh
:
#!/bin/bash
NORMAL_SLEEP=5
SHORT_SLEEP=2
CUR_SLEEP=''
while :
do
if [ -f /tmp/myfile ]; then
echo "myfile still exists. Next check in 5min"
CUR_SLEEP=$NORMAL_SLEEP
else
echo "myfile disappeared. Check again in 30s!"
CUR_SLEEP=$SHORT_SLEEP
echo "/tmp/myfile was removed. Check this!" \
| mailx -s "alert: myfile missed" johndoe@somewhere.com
fi
trap 'kill $SLEEP_PID; exit 1' 15
sleep $CUR_SLEEP &
SLEEP_PID=$!
wait
done
我可能给 johndoe@somewhere.com
发了一些邮件,但没关系。