代码之家  ›  专栏  ›  技术社区  ›  Fravadona

如何检测“while read-t TIMEOUT”循环因超时而退出?

  •  2
  • Fravadona  · 技术社区  · 5 月前

    如何检测a while read -t TIMEOUT 循环因超时而退出?

    例如:

    #!/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?'
    }
    
    2 回复  |  直到 5 月前
        1
  •  3
  •   Philippe    5 月前

    商场 read 在变量中的状态:

    {
        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"
    }
    

    适用于bash 3.2

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

    从Bash帮助文件中读取:

    -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
    

    注: 退出状态大于128 如果超过超时时间

    (这是Bash 5.2)

    您还可以查看 THIS.