1

This question is related only to bash, no ssh or any other tool.

I would like to detect a bash timeout, and only a timeout: I am NOT interested in any other exit conditions (exit, EOF, ^D, or termination by any signal)

If you set the timeout variable:

$ TMOUT=10

When a timeout occurs, the following is displayed:

$ timed out waiting for input: auto-logout

This is put by bash itself, as seen in the implementation here

But appart from that console message, I have not found any way to detect that a timeout occured. I have tried the following code:

export TMOUT=10

function handle-termination {
    local retvalue=$1
    echo "retvalue=$retvalue"
    env > /tmp/env
    if [ "$retvalue" = "$(kill -l ALRM)" ] ; then
        echo "Timeout"
    else
        echo "Exit"
    fi
}

trap 'handle-termination $?' EXIT

Hoping that the return code $? from the timeout would provide an indication, but it is always 0, no matter if a timeout or a manual exit triggered the EXIT signal.

Is there any way of reliably detecting detecting a bash session timeout?

1

You could write a "timeout counter" into a function and if it finishes first, it'll kill the script, otherwise the function itself will be killed.

run_tout_counter() {
    sleep 10 & wait
    echo timeout
    rm /tmp/toutPID
    kill -s SIGINT $processPID
}
export processPID=$$
run_tout_counter &  echo $! > /tmp/toutPID

read -p "type input:" A &&  ps $(cat /tmp/toutPID)  >/dev/null

excode=$?
if [[ $excode == 0 ]] ; then kill -s SIGINT $(cat /tmp/toutPID)  ; fi && rm /tmp/toutPID

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.