bash

How to detect that a `while read -t TIMEOUT` loop exited because of the timeout?


How to detect that a while read -t TIMEOUT loop exited because of the timeout?

For example:

#!/bin/bash

{
    echo # first line
    sleep 2
    echo # last line
} | {
    while read -t 1; do :; done
    echo 'Did it time out or did it reach eof?'
}

Solution

  • Store read status in a vairable :

    {
        echo # first line
        sleep 2
        echo # last line
    } | {
        while read -t 1; ret=$?; test $ret = 0; do :; done
        echo "Did it time out or did it reach eof? ret=$ret"
    }
    

    For bash 3.2

    while unset REPLY; read -t 1; do
        :
    done
    test -n "${REPLY+x}" && echo end of file || echo timeout