Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use timeout command with a own function?

I would like to use the timeout command with an own function, e.g.:

#!/bin/bash
function test { sleep 10; echo "done" }

timeout 5 test

But when calling this script, it seems to do nothing. The shell returns right after I started it.

Is there a way to fix this or can timeout not be used on own functions ?

like image 900
John Threepwood Avatar asked Nov 22 '25 16:11

John Threepwood


2 Answers

One way is to do

timeout 5 bash -c 'sleep 10; echo "done"'

instead. Though you can also hack up something like this:

f() { sleep 10; echo done; }
f & pid=$!
{ sleep 5; kill $pid; } &
wait $pid
like image 54
geirha Avatar answered Nov 25 '25 11:11

geirha


timeout doesn't seem to be a built-in command of bash which means it can't access functions. You will have to move the function body into a new script file and pass it to timeout as parameter.

like image 30
Aaron Digulla Avatar answered Nov 25 '25 09:11

Aaron Digulla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!