[SOLVED] Execute a shell function with timeout

Issue

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?

Solution

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.

Answered By – Douglas Leeder

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.