Why would this work
timeout 10s echo \"foo bar\" # foo bar
but this wouldn\'t
function echoFooBar {
echo \"foo bar\"
}
e
Putting my comment to Tiago Lopo's answer into more readable form:
I think it's more readable to impose a timeout on the most recent subshell, this way we don't need to eval a string and the whole script can be highlighted as shell by your favourite editor. I simply put the commands after the subshell with eval has spawned into a shell-function (tested with zsh, but should work with bash):
timeout_child () {
trap -- "" SIGTERM
child=$!
timeout=$1
(
sleep $timeout
kill $child
) &
wait $child
}
Example usage:
( while true; do echo -n .; sleep 0.1; done) & timeout_child 2
And this way it also works with a shell function (if it runs in the background):
print_dots () {
while true
do
sleep 0.1
echo -n .
done
}
> print_dots & timeout_child 2
[1] 21725
[3] 21727
...................[1] 21725 terminated print_dots
[3] + 21727 done ( sleep $timeout; kill $child; )