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

sh/bash/dash/ksh/zsh等Shell脚本
回复
头像
c\nc
帖子: 231
注册时间: 2007-12-25 12:51

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

#1

帖子 c\nc » 2009-09-10 12:14

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

怎么实现起来最简单呢? :em68
aerofox
帖子: 1453
注册时间: 2008-05-24 8:30

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

#2

帖子 aerofox » 2009-09-10 15:45

一个简单但不精确的方法:

代码: 全选

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] 后面的命令改为关机命令。
头像
c\nc
帖子: 231
注册时间: 2007-12-25 12:51

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

#3

帖子 c\nc » 2009-09-10 22:08

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……
头像
cnkilior
论坛版主
帖子: 4984
注册时间: 2007-08-05 17:40

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

#4

帖子 cnkilior » 2009-09-11 11:38

这个循环还能慢慢跑啊,没有sleep这么能控制时间呢?

一旦sleep了,程序就不能接受输入了。所以,必定是双进程的脚本!
aerofox
帖子: 1453
注册时间: 2008-05-24 8:30

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

#5

帖子 aerofox » 2009-09-11 20:01

楼上的试过就知道行不行了,要在 bash 中试,不要太老的版本就行。
read 中的 -t1 就是等一秒。
头像
c\nc
帖子: 231
注册时间: 2007-12-25 12:51

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

#6

帖子 c\nc » 2009-09-11 20:13

-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.
头像
O_O_BOT
帖子: 2461
注册时间: 2009-05-20 19:32

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

#7

帖子 O_O_BOT » 2009-09-11 23:34

cnkilior 写了:这个循环还能慢慢跑啊,没有sleep这么能控制时间呢?

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

如果要ms 的 就要 双进程了

或者自己弄个read
viewtopic.php?f=21&t=220283&start=30
这里有一个
irc 聊天室
ubuntu-cn 的irc 频道为
irc.ubuntu.com 8001 #ubuntu-cn
UTF8编码 可用 irssi xchat pidgin weechat 登录

http://webchat.freenode.net/?channels=ubuntu-cn
[url]irc://irc.freenode.net/ubuntu-cn[/url]
头像
eexpress
帖子: 58428
注册时间: 2005-08-14 21:55
来自: 长沙

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

#8

帖子 eexpress » 2009-09-11 23:37

又学究了。
不问下lz,这干嘛。
多半实现的方法,没找对路数。
瞎折腾
● 鸣学
头像
c\nc
帖子: 231
注册时间: 2007-12-25 12:51

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

#9

帖子 c\nc » 2009-09-11 23:54

没什么用途,来学习的 :em04
回复