I need to create a cron job that runs a bash script in background which does not end unless killed. The bash starts a process that should keep running for about 28 hours then I need another cron job to kill it. First cron runs every day at 0:00AM, starts the process. Second cron runs at 4:00AM and has to kill the process started the day before, leaving the one for the current day to run.

From what I searched, I should store the pid of the process in a file and then have the second cron access it but how and where? In the cron or in bash? Considering the process started by bash script does not end until killed, will the commands after ever execute?

EDIT: Ipor Sircer's solution solves the particular problem I have but I'd still like to learn how to export the PID in a file which another CRON can access.

  • 3
    Exactly 28 hours? If so, just run timeout 28h yourcronjobhere
    – thrig
    Dec 29, 2016 at 17:54
  • Argh, too late to edit… echo "kill $$" | at 4am tomorrow if you're strict about the time of day (otherwise, yes, prefer timeout). Dec 29, 2016 at 18:02
  • 28 hours should be enough to finish. ok where does the echo kill command go? In the bash script? So the commands that come after the process start are still executed? Should I use & after the process in the bash script?
    – UrVal
    Dec 29, 2016 at 18:15
  • 1
    I'm going to be obnoxious and point out that there's probably a better way to d whatever it is you're trying to do.
    – user2267
    Dec 29, 2016 at 20:00

1 Answer 1


Use timeout command, it is much easier:

0 0 * * * timeout 28h /home/script.sh

PS. Remember to use the full path in the crontab.

  • wow, this is an unexpected solution, no need to complicate it with 2 crons if one can do the job. I'd accept your answer but I'm really curious to know how the PID can be exported in this situation can you help with this as well?
    – UrVal
    Dec 29, 2016 at 18:07
  • Also, I'd uprate but I don't have the 15 reputation minimum yet :(
    – UrVal
    Dec 29, 2016 at 18:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .