3

How do I repeatedly start and kill a bash script that takes a long time. I have a analyze_realtime.sh that runs indefinitely, but I only want to run it for X second bursts (just say 15s for now).

while true; do analyze_realtime.sh; sleep 15; done

The problem with this is that analyze_realtime.sh never finishes, so this logic doesn't work. Is there a way to kill the process after 15 seconds, then start it again?

I was thinking something with analyze_realtime.sh&, ps, and kill may work. Is there anything simpler?

SwimBikeRun
  • 4,192
  • 11
  • 49
  • 85

3 Answers3

3

Try this out

while true; do
    analyze_realtime.sh & # put script execution in background
    sleep 15
    kill %1
done

Explanation

%1 refer to the latest process ran in background

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
3
 while true;
 do
   analyze_realtime.sh &
   jobpid=$! # This gets the pid of the bg job
   sleep 15
   kill $jobpid
   if ps -p $jobpid &>/dev/null; then
     echo "$jobpid didn't get killed. Moving on..." 
   fi
 done

You can do more under the if-statement, sending other SIGNALs if SIGHUP didn't work.

iamauser
  • 11,119
  • 5
  • 34
  • 52
1

You can use timeout utility from coreutils:

while true; do
    timeout 15 analyze_realtime.sh
done

(Inspired by this answer)

Yoory N.
  • 4,881
  • 4
  • 23
  • 28