开发者

How to implement a timer keypress in bash?

Here's what will happen, a message is displayed with a specified time waiting for keypress, if no keypress then it will resume.

Example

"Press ESC to exit, otherwise you will die.. 3..2..1"

"Press 'x' to procrastinate and check email, read some blogs, facebook, twitter.. otherwise you will resume work for 12 hours.. 3..2..1"

This should be a really handy function. 开发者_如何转开发How do I create this functionality in bash?


Look on the bash man page for the "read" command and notice the "-t timeout" option. Something like this should get you started

for i in 3 2 1 ; do 
    read -p $i... -n 1 -t 1 a && break
done


Use the -t and -n options of the read bash builtin command, also do not forget -r and -s. (see the manual for details)

#!/bin/bash

timeout=3

echo -n "Press ESC to exit, otherwise you will die..."
while [ $timeout -gt 0 ]; do
    echo -n " $timeout"
    if read -n1 -t1 -r -s x; then
        echo
        exit 0
    fi
    let timeout--
done
echo
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜