Tuesday 13 March 2018

linux - Is there a way to display a countdown or stopwatch timer in a terminal?


How can I display a real-time countdown timer on the Linux terminal? Is there an existing app or, even better, a one liner to do this?



Answer



I'm not sure why you need beep, if all you want is a stopwatch, you can do this:


while true; do echo -ne "`date`\r"; done

That will show you the seconds passing in realtime and you can stop it with Ctrl+C. If you need greater precision, you can use this to give you nanoseconds:


while true; do echo -ne "`date +%H:%M:%S:%N`\r"; done

Finally, if you really, really want "stopwatch format", where everything starts at 0 and starts growing, you could do something like this:


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

For a countdown timer (which is not what your original question asked for) you could do this (change seconds accordingly):


seconds=20; date1=$((`date +%s` + $seconds)); 
while [ "$date1" -ge `date +%s` ]; do
echo -ne "$(date -u --date @$(($date1 - `date +%s` )) +%H:%M:%S)\r";
done



You can combine these into simple commands by using bash (or whichever shell you prefer) functions. In bash, add these lines to your ~/.bashrc (the sleep 0.1 will make the system wait for 1/10th of a second between each run so you don't spam your CPU):


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

You can then start a countdown timer of one minute by running:


countdown 60

You can countdown two hours with:


countdown $((2*60*60))

or a whole day using:


countdown $((24*60*60))

And start the stopwatch by running:


stopwatch



If you need to be able to deal with days as well as hours, minutes and seconds, you could do something like this:


countdown(){
date1=$((`date +%s` + $1));
while [ "$date1" -ge `date +%s` ]; do
## Is this more than 24h away?
days=$(($(($(( $date1 - $(date +%s))) * 1 ))/86400))
echo -ne "$days day(s) and $(date -u --date @$(($date1 - `date +%s`)) +%H:%M:%S)\r";
sleep 0.1
done
}
stopwatch(){
date1=`date +%s`;
while true; do
days=$(( $(($(date +%s) - date1)) / 86400 ))
echo -ne "$days day(s) and $(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)\r";
sleep 0.1
done
}

Note that the stopwatch function hasn't been tested for days since I didn't really want to wait 24 hours for it. It should work but please let me know if it doesn't.


No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...