Execute a shell function with timeout

前端 未结 10 1138
死守一世寂寞
死守一世寂寞 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条回答
  •  孤街浪徒
    2020-12-01 01:10

    You can create a function which would allow you to do the same as timeout but also for other functions:

    function run_cmd { 
        cmd="$1"; timeout="$2";
        grep -qP '^\d+$' <<< $timeout || timeout=10
    
        ( 
            eval "$cmd" &
            child=$!
            trap -- "" SIGTERM 
            (       
                    sleep $timeout
                    kill $child 2> /dev/null 
            ) &     
            wait $child
        )
    }
    

    And could run as below:

    run_cmd "echoFooBar" 10
    

    Note: The solution came from one of my questions: Elegant solution to implement timeout for bash commands and functions

提交回复
热议问题