分页: 1 / 1

问题:实现倒计时+按任意键退出

发表于 : 2009-09-10 12:14
c\nc
要实现的效果:
屏幕上打印出并自动刷新倒计时提示,如“还剩 XX 秒关机……”,同时可以接受用户按任意键结束倒计时退出。

怎么实现起来最简单呢? :em68

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-10 15:45
aerofox
一个简单但不精确的方法:

代码: 全选

n=30
while true; do
    echo -n -e "\r还剩 $((n--)) 秒关机 ....  "
    read -esr -n1 -t1 && break
    [ $n -eq 0 ] && echo -e "\n正在关机"&& break
done
实际使用时把 [$n -eq 0] 后面的命令改为关机命令。

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-10 22:08
c\nc
aerofox 写了:一个简单但不精确的方法:

代码: 全选

n=30
while true; do
    echo -n -e "\r还剩 $((n--)) 秒关机 ....  "
    read -esr -n1 -t1 && break
    [ $n -eq 0 ] && echo -e "\n正在关机"&& break
done
实际使用时把 [$n -eq 0] 后面的命令改为关机命令。
学习了,强大的read……

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-11 11:38
cnkilior
这个循环还能慢慢跑啊,没有sleep这么能控制时间呢?

一旦sleep了,程序就不能接受输入了。所以,必定是双进程的脚本!

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-11 20:01
aerofox
楼上的试过就知道行不行了,要在 bash 中试,不要太老的版本就行。
read 中的 -t1 就是等一秒。

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-11 20:13
c\nc
-t timeout
Cause read to time out and return failure if a complete line of
input is not read within timeout seconds. timeout may be a decimal
number with a fractional portion following the decimal point. This
option is only effective if read is reading input from a terminal,
pipe, or other special file; it has no effect when reading from reg‐
ular files. If timeout is 0, read returns success if input is
available on the specified file descriptor, failure otherwise. The
exit status is greater than 128 if the timeout is exceeded.

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-11 23:34
O_O_BOT
cnkilior 写了:这个循环还能慢慢跑啊,没有sleep这么能控制时间呢?

一旦sleep了,程序就不能接受输入了。所以,必定是双进程的脚本!
read 是可以 的 不过是 秒级的

如果要ms 的 就要 双进程了

或者自己弄个read
viewtopic.php?f=21&t=220283&start=30
这里有一个

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-11 23:37
eexpress
又学究了。
不问下lz,这干嘛。
多半实现的方法,没找对路数。
瞎折腾

Re: 问题:实现倒计时+按任意键退出

发表于 : 2009-09-11 23:54
c\nc
没什么用途,来学习的 :em04