我正在读取特定模式的日志文件,例如播放、暂停、停止等。
我想只在我读到一个 STOP 而在接下来的 5 秒内没有跟随 PLAY 时执行某个脚本。
这是我的代码:
#!/bin/bash
tail -Fn0 /tmp/player.log | \
while read line ; do
echo "$line" | grep -q "PLAYER STATE CHANGE: "
if [ $? = 0 ]
then
# If playing
echo "$line" | grep -q "PLAY"
if [ $? = 0 ]
then
echo "Started PLAYING!"
kill -INT $pid
fi
# If paused
echo "$line" | grep -q "PAUSE"
if [ $? = 0 ]
then
echo "PAUSED!"
defer_switch_off.sh &
pid=$!
fi
# If stopped
echo "$line" | grep -q "STOP"
if [ $? = 0 ]
then
echo "STOPPED!"
defer_switch_off.sh &
pid=$!
fi
fi
done
这是我的defer_switch_off.sh
#!/bin/bash
trap 'kill -INT $pid' INT
timeout 10 sh -c 'sleep 5; switch_off.sh' &
pid=$!
wait $pid
我遇到的问题是,当 PLAY
跟在 STOP
在 5 秒的时间跨度内,如我所愿。脚本仍然被执行。
最佳答案
在您的脚本中,每次在看到 STOP 后看到 PLAY 时,您都需要检查自启动 deferred_switch_off.sh
以来经过了多长时间。
if [[ $line =~ PLAY ]]; then
if (( pid && SECONDS < 5 )); then
kill -INT "$pid"
unset pid
fi
elif [[ $line =~ STOP ]]; then
SECONDS=0
defer_switch_off.sh &
pid=$!
elif ...
SECONDS
是一个每秒递增的 bash
shell 变量。
另一种方法是在每次看到 STOP 时记录时间戳,如果 pid
不为零,则检查 PLAY 行上的时间戳。如果您不是实时阅读日志,这可能会有所不同。
关于linux - 有条件地终止延迟脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459750/