admin管理员组

文章数量:1123138

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?'
}

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?'
}
Share Improve this question edited 6 hours ago Fravadona asked 6 hours ago FravadonaFravadona 16.5k1 gold badge26 silver badges43 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

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    

From the Bash help file for read:

-t timeout  time out and return failure if a complete line of
        input is not read within TIMEOUT seconds.  The value of the
        TMOUT variable is the default timeout.  TIMEOUT may be a
        fractional number.  If TIMEOUT is 0, read returns
        immediately, without trying to read any data, returning
        success only if input is available on the specified
        file descriptor.  The exit status is greater than 128
        if the timeout is exceeded

Note The exit status is greater than 128 if the timeout is exceeded

(This is Bash 5.2)

You can also look at THIS.

本文标签: bashHow to detect that a while read t TIMEOUT loop exited because of the timeoutStack Overflow