How to self-terminate a bash script after timeout?

The timeout utility that is a part of GNU coreutils does it for you:

timeout 5m bash script.sh

would terminate the script after 5 minutes of execution.


You get the PID with PID=$$.

What you want may be most easily achieved with the command timeout.

But you can run a background process, too:

(sleep $TIMEOUT && kill "$PID") &

If you always want the script to timeout after 5 minutes, you can simply use a block in a background process like this. If you use Ctrl+C while it's running, the background process will also terminate:

#!/bin/bash
{
    sleep 5m
    kill $$
} &

while true
do
    date
    sleep 1
done