How to use Bash read with a timeout?

后端 未结 3 462
不知归路
不知归路 2020-12-04 17:09

I can ask the user to press Enter by using read, and have him wait by calling sleep. But I can’t think of a way of doing both at the sam

相关标签:
3条回答
  • 2020-12-04 18:08

    In bash, read has a -t option where you can specify a timeout. From the manpage:

    read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...]

    -t timeout: cause read to time out and return failure if a complete line of input is not read within timeout seconds. This option has no effect if read is not reading input from the terminal or a pipe.

    Transcript below (without hitting ENTER):

    $ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; echo ; date
    Tue Feb 28 22:29:15 WAST 2012
    Hit ENTER or wait ten seconds
    Tue Feb 28 22:29:25 WAST 2012
    

    Another, hitting ENTER after a couple of seconds:

    $ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; date
    Tue Feb 28 22:30:17 WAST 2012
    Hit ENTER or wait ten seconds
    Tue Feb 28 22:30:19 WAST 2012
    

    And another, hitting CTRL-C:

    $ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; echo ; date
    Tue Feb 28 22:30:29 WAST 2012
    Hit ENTER or wait ten seconds
    
    0 讨论(0)
  • 2020-12-04 18:11

    From the bash reference manual :

    read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt][-t timeout][-u fd] [name ...]

    0 讨论(0)
  • 2020-12-04 18:13

    The read builtin has a timeout.

    read -t 10
    

    will do it

    0 讨论(0)
提交回复
热议问题