Execute a shell function with timeout Execute a shell function with timeout shell shell

Execute a shell function with timeout


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

export -f echoFooBartimeout 10s bash -c echoFooBar


timeout is a command - so it is executing in a subprocess of your bash shell. Therefore it has no access to your functions defined in your current shell.

The command timeout is given is executed as a subprocess of timeout - a grand-child process of your shell.

You might be confused because echo is both a shell built-in and a separate command.

What you can do is put your function in it's own script file, chmod it to be executable, then execute it with timeout.

Alternatively fork, executing your function in a sub-shell - and in the original process, monitor the progress, killing the subprocess if it takes too long.


There's an inline alternative also launching a subprocess of bash shell:

timeout 10s bash <<EOTfunction echoFooBar {  echo foo}echoFooBarsleep 20EOT