Bash break while loop by user input

假装没事ソ 提交于 2019-12-14 02:59:12

问题


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?


回答1:


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 $!
}


来源:https://stackoverflow.com/questions/35310972/bash-break-while-loop-by-user-input

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