Reputation: 1240
Is there a way to create a bash script that will only run for X hours? I'm currently setting up a cron job to initiate a script every night. This script essentially runs until a certain condition is met, exporting it's status to a holding variable to keep track of 'where it is' after each iteration. The intention is to start-up the process every night, run for a few hours, and then stop, holding the status until the process starts up the next night.
Short of somehow collecting the start time, and checking it against the current time in each iteration of the loop, is there an easier way to do this? Bash scripting is not my forte (I know enough to get things done and be dangerous) and I have not done something like this before. Any help would be appreciated. Thanks.
Upvotes: 0
Views: 953
Reputation: 189749
By using the SIGALRM
facility you can rig a signal to be sent after a certain time, but traditionally, this was not easily accessible from shell scripts (people would write small custom C or Perl programs for this). These days, GNU coreutils
ships with a timeout
command which does this by wrapping your command:
timeout 4h yourprogram
Upvotes: 0
Reputation: 84423
GNU coreutils contains an actual timeout binary, usually invoked like this:
# timeout after 5 seconds when sleeping for 30
/usr/bin/timeout 5s /bin/sleep 30
In your case, you'd want to specify hours instead of seconds, so to timeout in 2 hours use something like 2h
instead of 5s
. See timeout(1) or info coreutils 'timeout invocation'
for additional options.
Native timeouts or the GNU timeout command are really the best options. However, see the following for some ideas if you decide to roll your own:
Upvotes: 1
Reputation: 63962
Do it as you described - it is the cleanest way.
But if for some strange reason want kill the process after a time, can use the next
./long_runner &
(sleep 5; kill $!; wait; exit 0) &
will kill the long_runner
after 5 secs.
Upvotes: 1