Bash break while loop by user input

2019-08-06 12:55发布

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条回答
Animai°情兽
2楼-- · 2019-08-06 13:24

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 $!
}
查看更多
登录 后发表回答