2

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 Answer 1

3

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 $!
}
Sign up to request clarification or add additional context in comments.

1 Comment

This kind of contains the output. Looks like this: ~$ stopwatch test test [1] 3606 00:00:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.