Reed_Xia Reed_Xia - 1 year ago 41
Linux Question

Set timeout for shell script, to make it exit(0) when time is over

When I set up a Jenkins job and found a problem about timeout for shell script.

It works like this:

Start Jenkins →
is launched →
is launched in

Part code of
is like:


export TIMEOUT=30
# set timeout as 30s for

( ( sleep $TIMEOUT && function_Timeout ) & ./ )
# this line of code is in a = loop actually
# it will launch, one by one
# later, I want to set 30s time out for each of them.

function_Timeout() {
if [ ! -f test1_result_file]: then
# the test1_result_file will not
# be created if is not finished executing.

part of is as below

function trap_fun() {
{ if [ $TRAP_CODE -ne 0 ]; then
echo "test aborted"
echo "test completed"
} 2>/dev/null

trap "trap_fun" EXIT

is launched by Jenkins job, the whole
will be terminated when time is over, and the line of
is reached, and the Jenkins job stop and fail.

I guess it's because
is killed and exit code is not
, so it cause this problem.

So my question is, is there someway to terminate or end the sub-script (launched by the main one, like
in my case) exit with code

Updated on July 1:

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

I added more details. I did a lot google job but still not found a proper way to resolve this problem:(

Thanks for your kind help!

Answer Source

I resolved this problem finally, I added the code below in each

trap 'exit ' SIGTERM SIGHUP

It is to make exit normally after it receives killall signal.

Thanks to all the help!