title: Set timeout for shell script, to make it exit(0) when time is over
body: <p>When I set up a Jenkins job and found a problem about timeout for shell script.</p>
  
  <p>It works like this:</p>
  
  <p>Start Jenkins → <code>control.sh</code> is launched → <code>test1.sh</code> is launched in <code>control.sh</code></p>
  
  <p>Part code of <code>control.sh</code> is like:</p>
  
  <pre><code>#!/bin/sh
  source func.sh     
  
  export TIMEOUT=30
  # set timeout as 30s for test1.sh
  
  ( ( sleep $TIMEOUT &amp;&amp; function_Timeout ) &amp; ./test1.sh ) 
  # this line of code is in a = loop actually
  # it will launch test2.sh, test3.sh... one by one
  # later, I want to set 30s time out for each of them.
  
  function_Timeout() {
    if [ ! -f test1_result_file]: then
      killall test1.sh
      # the test1_result_file will not 
      # be created if test1.sh is not finished executing.
    fi
  }
  </code></pre>
  
  <p>part of func.sh is as below</p>
  
  <pre><code>#!/bin/sh
  function trap_fun() {
    TRAP_CODE=$?
    { if [ $TRAP_CODE -ne 0 ]; then
        echo "test aborted"
      else
        echo "test completed"
    } 2&gt;/dev/null
  
  trap "trap_fun" EXIT
  </code></pre>
  
  <p>After <code>control.sh</code> is launched by Jenkins job, the whole <code>control.sh</code> will be terminated when time is over, and the line of <code>killall test1.sh</code> is reached, and the Jenkins job stop and fail.</p>
  
  <p>I guess it's because <code>test1.sh</code> is killed and exit code is not <code>0</code>, so it cause this problem.</p>
  
  <p>So my question is, is there someway to terminate or end the sub-script (launched by the main one, like <code>control.sh</code> in my case) exit with code <code>0</code>?</p>
  
  <p>Updated on July 1: </p>
  
  <p>Thanks for the answers so far, I tried @Leon's suggestion, but I found the code 124 sent by timeout's kill action, is still caught by the trap code - trap "trap_fun" EXIT, which is in func.sh.</p>
  
  <p>I added more details. I did a lot google job but still not found a proper way to resolve this problem:(</p>
  
  <p>Thanks for your kind help!</p>