Paul A Jungwirth
Paul A Jungwirth

Reputation: 24551

bash: run a command for n minutes, then SIGHUP it

Is there any bash/linux command to launch a long-running command, then kill it after n minutes? I guess I could hack something up with perl using fork and kill, but does anyone know of something already out there?

Upvotes: 22

Views: 14847

Answers (3)

pixelbeat
pixelbeat

Reputation: 31748

See the timeout command now in most GNU/Linux distros.

timeout -sHUP 10m command

The same functionality can be achieved with http://www.pixelbeat.org/scripts/timeout

Upvotes: 43

SiegeX
SiegeX

Reputation: 140417

n=5
some_command &
pid=$!
at now + $n minutes <<<"kill -HUP $pid"

The benefit of using at over waiting for sleep is that your script wont block waiting for the sleep to expire. You can go and do other things and at will asynchronously fire at the specified time. Depending on your script that may be a very important feature to have.

Upvotes: 12

Marcus Borkenhagen
Marcus Borkenhagen

Reputation: 6656

Try it with this one, it starts your command in the background, stores it's PID in $P, waits for some time and kills it with a SIGHUP.

yourCommand & PID=$!
sleep ${someMinutes}m
kill -HUP $PID

Cheers

PS: that assumes a sleep that knows about Nm (minutes), else, you might want to do some math :)

Upvotes: 20

Related Questions