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
use
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.