Limited lifetime scripts

While helping Xavi with a small task (batch converting ODT documents to PDF via a web form), I’ve remembered a little recipe I’ve written some time ago.

It’s a way to force some script to die after a defined timeout. So, you can perform a command by ssh inside a script or perform any blocking task you want, and it will always return.

The only thing you have to do is to put these single 3 lines of code at the start of your bash script:

SECURITY_TIMEOUT=60
CMD_PID="$$";
{ sleep $SECURITY_TIMEOUT; kill -9 $CMD_PID; } 2>/dev/null &
Enjoy it!