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
  • 3,802
  • 10
  • 47
  • 81

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 Quenot
  • 154,891
  • 35
  • 213
  • 206
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
  • 10,437
  • 5
  • 28
  • 49
1

You can use timeout utility from coreutils:

while true; do
    timeout 15 analyze_realtime.sh
done

(Inspired by this answer)

Yoory N.
  • 4,034
  • 4
  • 20
  • 26