我正在读取某些模式的日志文件,例如PLAY,PAUSE,STOP等。
我想在我读取一个在接下来的5秒内没有播放的STOP时执行某个脚本。
这是我的代码:
#!/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
我遇到的问题是,当kill
在5秒的时间内跟随deferred_switch_off.sh
时,我无法PLAY
STOP
脚本我想要。该脚本仍然被执行。
答案 0 :(得分:1)
在你的脚本中,你需要检查自从你看到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行上的时间戳。如果您没有实时读取日志,这可能会有所不同。