Timeout a process in Bash > v4

Posted by – 19/04/2012

Just for reference, this is really useful:

( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec some_command )

Update Apr 20, 2012 @ 16:54: As pointed in a comment by Timo Juhani Lindfors, if “some_command” exits early and the interval is long, another process can reuse its process number and get killed once the sleep runs out. Does anybody know a better way of doing that without using timeout from coreutils (better yet: using just bash)?

11 Comments on Timeout a process in Bash > v4

  1. VideoPortal says:

    As Douglas Leeder said you need a separate process for timeout to signal to. Workaround by exporting function to subshells and running subshell manually.

  2. Ben Hutchings says:

    The secret is to be the parent:


    some_command & child_pid=$!
    trap true ALRM
    parent_pid=$$
    (sleep 10 && kill -ALRM $parent_pid) & alarm_pid=$!
    wait $child_pid
    if [ $? -gt 128 ]; then
    # timed out
    kill $child_pid
    else
    # cancel timeout
    kill $alarm_pid
    fi

    As a bonus, this works in dash and probably any POSIX shell.

    • spectra says:

      @Ben,

      Yep… but that is much longer and hard to remember than a single line. But good point: be the parent and the pid will not be reused.

  3. Patrick says:

    There’s killall if you don’t mind killing all processes with that name.

  4. Timo Juhani Lindfors says:

    if some_command exits before 10 seconds isn’t there the problem that the pid could get reused and you would kill a completely unrelated process?

    • spectra says:

      @Timo,

      Actually the problem you described will happen. I guess if we’re talking about a 10 seconds timeout, hardly the process number will be reused. But if the timeout is larger, that will happen.

  5. tfe says:

    the command “timeout 10s command” will do the job too 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *