Reed_Xia Reed_Xia - 5 months ago 7
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 →

control.sh
is launched →
test1.sh
is launched in
control.sh


Part code of
control.sh
is like:

#!/bin/sh
source func.sh

export TIMEOUT=30
# set timeout as 30s for test1.sh

( ( sleep $TIMEOUT && function_Timeout ) & ./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
}


part of func.sh is as below

#!/bin/sh
function trap_fun() {
TRAP_CODE=$?
{ if [ $TRAP_CODE -ne 0 ]; then
echo "test aborted"
else
echo "test completed"
} 2>/dev/null

trap "trap_fun" EXIT


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

I guess it's because
test1.sh
is killed and exit code is not
0
, 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
control.sh
in my case) exit with code
0
?

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 func.sh.

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

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

trap 'exit ' SIGTERM SIGHUP

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

Thanks to all the help!