How to implement a timer keypress in bash?

穿精又带淫゛_ 提交于 2019-12-08 03:30:40

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/1943748/how-to-implement-a-timer-keypress-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!