我有一个运行bash脚本的任务调度器。该任务首先打开一个GIT Bash终端,显示一条打开消息(“脚本将在60秒后开始”),并在倒计时结束时运行一个脚本。
现在,我想改善用户体验,允许他/她停止/恢复倒计时或(没有任何干预)离开脚本自动运行。这就是程序流程:
1.在GIT Bash终端打开后,允许用户通过按ENTER或任何其他键在所示的时间范围内暂停脚本;
1.如果用户没有采取任何行动,倒计时将继续,脚本将在时间框架结束时运行;
1.如果用户已经按下ENTER(或任何其他键),则通过再次按下ENTER(或任何其他键),他/她恢复倒计时,并且将立即运行。
我试过使用read -p
,但它对我不好:我不希望用户操作触发什么,而是停止/暂停倒计时(然后恢复)。
1条答案
按热度按时间rkkpypqq1#
更新历史记录:
可暂停倒计时
结合一些类似问题here的提示和一些关于如何读取单个字符(e.g. here, otherwise everywhere on the internet)的外部资源,并添加一个额外的循环用于恢复,这就是我的想法:
这可以保存并作为独立脚本运行。该功能可以在其他地方重复使用。它用
SPACE
暂停/恢复,因为这对我来说似乎更直观,因为它是如何工作的。嵌入在浏览器中的视频播放器。倒计时也可以通过按空格键以外的键来加速(这是一个功能)。
发出警告消息并等待可暂停超时
以下变体实现了一个 pausable timeout,它只打印初始警告消息,除非用户通过按空格键暂停或恢复(内部)倒计时:
可暂停倒计时,更新同一行
这是一个类似于第一个倒计时,但它只需要一行。依靠
echo -e
擦除和覆盖以前打印的消息。如果线条比控制台宽度长,这个命令可能会表现得很奇怪(它不会完全擦除线条)。
未分类的收集提示的任何人谁试图使某事。相似:
IFS= read -n1
读取单个字符read -t <seconds>
为read
设置超时。一旦超时过期,read
将以非零值退出,并将变量设置为空。$SECONDS
以秒为单位测量从脚本开始的时间。echo -n
打印,那么它可以用echo -ne "\033[1K\r"
擦除和重置。