Execute a shell function with timeout

前端 未结 10 1125
死守一世寂寞
死守一世寂寞 2020-12-01 00:40

Why would this work

timeout 10s echo \"foo bar\" # foo bar

but this wouldn\'t

function echoFooBar {
  echo \"foo bar\"
}

e         


        
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 01:12

    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; )
    

提交回复
热议问题