Execute a shell function with timeout

speendo picture speendo · Mar 31, 2012 · Viewed 97.8k times · Source

Why would this work

timeout 10s echo "foo bar" # foo bar

but this wouldn't

function echoFooBar {
  echo "foo bar"
}

echoFooBar # foo bar

timeout 10s echoFooBar # timeout: failed to run command `echoFooBar': No such file or directory

and how can I make it work?

Answer

Douglas Leeder picture Douglas Leeder · Mar 31, 2012

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.