击断while循环由用户输入 [英] Bash break while loop by user input

查看:144
本文介绍了击断while循环由用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了我一个小秒表,我投入.bashrc中有以下code:

 秒表(){
    DATE1 =`日期+%s`
    回声$ 1
    而真实的;做
            回声-ne$(日期-u --date @ $((`日期+%s` - $日期1))+%H:%M:%S)\\ r
    DONE
}

在输出中应该是这样的而时间也只是在第二行计数:

 〜$秒表测试
测试
00:00:04

现在,如果我想结束秒表我preSS按Ctrl + C,给了我这样的:

 〜$秒表测试
测试
^ C:00:03

我想结束循环,而使用例如含有它的输出中我的输入键或任何其他。
但是,如果我用读它会等待我的输入和保持定时器。

我如何保持循环运行,直到我preSS任何关键还是preserving输出?

编辑:我虽然它..
是否有可能退出前写的最后输出到文件?


解决方案

添加到123的回答,因为我不能发表评论。
而不是使用

 杀1%

使用

  $杀!

因为,有可能是壳上其他几个职位,杀1%能杀死其他工作一样,所以使其更灵活$!可以使用。

$!将返回进程ID的最后一个函数在当前shell跑去。


  

运行循环与和放背景;


  
  

然后读暂停功能。


  
  

写入并杀死进入时是pressed。


 秒表(){
DATE1 =`日期+%s`
回声$ 1
而真实的;做
        回声-ne$(日期-u --date @ $((`日期+%s` - $日期1))+%H:%M:%S)\\ r
完成&功放;

回声-ne$(日期-u --date @ $((`日期+%s` - $日期1))+%H:%M:%S)>文件
杀$!
}

I got me a little stopwatch which I put into bashrc with the following code:

stopwatch() {
    date1=`date +%s`
    echo $1
    while true; do
            echo -ne "$(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)\r"
    done
}

The ouput would look like this while the time would just count up in the second line:

~$ stopwatch test
test
00:00:04

Now if I want to end the stopwatch I press Ctrl+C which gives me this:

~$ stopwatch test
test
^C:00:03

I'd like to end the loop while containing its ouput using e.g. my enter-key or any other. However if I use read it would wait for my input and hold the timer.

How do I keep the loop running until I press any key still preserving the output?

Edit: While am at it.. Is it possible to write the last output to a file before exiting?

解决方案

Adding to 123's answer, since I cannot comment. Instead of using

kill %1

use

kill $!

since, there may be several other jobs on the shell, kill %1 can kill other jobs as well, so to make it more flexible $! can be used.

$! will return process ID of last function ran on the current shell.

Run the loop in the background with &

Then pause function with read.

Write and kill when enter is pressed.

stopwatch() {
date1=`date +%s`
echo $1
while true; do
        echo -ne "$(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)\r"
done &
read
echo -ne "$(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)" > file
kill $!
}

这篇关于击断while循环由用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆