Skip to main content

zonena.me

Timeout in a Shell Script

Although GNU coreutils includes a timeout command, sometimes that’s not available. There are a lot of ham fisted approaches by very intelligent people.

The “right” way to do this is with the ALRM signal. That’s what it’s for. So rather than reinvent the wheel, here’s a correctly working timeout function. This works in at least bash and zsh.

cleanup () {
  [[ -z $! ]] && kill -s TERM $!
  sleep 1
  [[ -z $! ]] && kill -s KILL $!
}

timeout () {
  ( sleep $1 ; kill -s ALRM $$ ) &
  shift
  "$@" &
  wait $!
}

trap cleanup ALRM
timeout 5 sleep 7

In this case, timeout 5 executes with timeout of 5 seconds and sleep 7 is the command to execute. This example will timeout. The timeout function will return with 142 if the process timed out.