如何在正在运行的bash脚本中更改SLEEP时间

时间:2017-03-01 13:23:45

标签: bash shell sleep

附录: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,但遗憾的是无法看到它如何解决我的问题。

1 个答案:

答案 0 :(得分:1)

我的机器上的代码运行正常。这是我跑的(改变时间值只是为了测试):

  • ./script.sh - > “myfile消失了。请在30多岁后再次检查!”以2秒的间隔打印
  • touch /tmp/myfile
  • ./script.sh - > “myfile仍然存在。下一次检查5分钟”以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发送一些邮件,但没关系。