title: Conditionally terminating a deferred script
body: <p>I'm reading a log file for certain patterns like PLAY, PAUSE, STOP, etc..</p>
  
  <p>I want to execute a certain script only when I read a STOP which isn't followed by a PLAY within the next 5 seconds. </p>
  
  <p>Here's my code:</p>
  
  <pre><code>#!/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 &amp;
              pid=$!
          fi
          # If stopped 
          echo "$line" | grep -q "STOP"
          if [ $? = 0 ]
          then
              echo "STOPPED!"
              defer_switch_off.sh &amp;
              pid=$!
          fi
      fi
  done
  </code></pre>
  
  <p>And here's my <code>defer_switch_off.sh</code></p>
  
  <pre><code>#!/bin/bash
  trap 'kill -INT $pid' INT
  timeout 10 sh -c 'sleep 5; switch_off.sh' &amp;
  pid=$!
  wait $pid
  </code></pre>
  
  <p>The problem I'm having is that I'm not able to <code>kill</code> the <code>deferred_switch_off.sh</code> script when a <code>PLAY</code> follows a <code>STOP</code> within a timespan of 5 seconds as I would like. The script still gets executed. </p>