129

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?

  • 3
    regarding SU hold: I think this falls under "computer software" without "asking for a shopping or product recommendation". I'm not asking for recommendations; I'm asking if something even exists. When I initially asked the question, I was anticipating maybe a "yeah there is this built-in -nix script". If I can restructure the question, I will. – tir38 Jun 26 '13 at 17:40
  • 1
    That's what I tried to do. It is on topic after my edit as far as I am concerned and I have voted to reopen it. – terdon Jun 26 '13 at 17:41
  • @terdon thanks, I see how that is a better question. – tir38 Jun 28 '13 at 2:19

20 Answers 20

169

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.

  • 7
    I added these nice functions to my .zshrc right after I read your answer. Today I used countdown the first time and noticed a rather high CPU usage. I added a sleep 0.1 (I don't know if a sleep time of a fractional second is supported on all systems) which improved that a lot. The drawback is of course a less accurate display accuracy, but I can live with a deviation of max. 100ms. – mpy Jul 5 '13 at 14:45
  • @mpy thanks for mentioning that. I am getting ~3% CPU usage when doing this in bash, I can live with that (though it is higher than I expected and I have also added the sleep to my own .bashrc). – terdon Jul 5 '13 at 14:59
  • @terdon: I must admit that I used it on a rather old machine (2007?!) and CPU went up to 18%... otherwise I probably wouldn't have noticed. – mpy Jul 5 '13 at 15:02
  • 2
    Just found this answer. I found putting the carriage return at the beginning of the echo statement in the stopwatch function was handy as it meant killing the stopwatch didn't overwrite the current stopwatch time: echo -ne "\r$(date -u --date @$((date +%s - $date1)) +%H:%M:%S)"; – mkingston Jun 16 '14 at 12:51
  • 3
    @chishaku: On OS X, this seemed to work for me: echo -ne "$(date -ju -f %s $(($date1 - date +%s)) +%H:%M:%S)\r"; – user1071847 Jul 11 '16 at 16:26
85

My favorite way is:

Start:

time cat

Stop:

ctrl+c

As @wjandrea commented below, another version is to run:

time read

and press Enter to stop

  • 1
    +1. Lifehacker featured this trick. – Nathan Arthur Sep 9 '15 at 22:18
  • 6
    similar, but you can press Enter to stop it: time read – wjandrea May 25 '16 at 1:07
  • 5
    time read fails in zsh, but time (read) works. – Sparhawk Oct 7 '16 at 4:53
  • Problem is though, that you cannot see the time without canceling it or finishing it. When you then restart it, the timer begins anew. – Zelphir Oct 18 '17 at 8:50
29

I was looking for the same thing and ended up writing something more elaborate in Python:

This will give you a simple 10-second countdown:

sudo pip install termdown
termdown 10

Source: https://github.com/trehn/termdown

  • 1
    @DoktoroReichard: Well, this is a download link. – harrymc Jun 6 '14 at 10:42
  • doesn't work with python 3.x – Suhaib Jun 20 '14 at 2:18
  • 1
    @Suhaib: It should and does for me. Please raise an issue on GitHub with more info. – trehn Jun 27 '14 at 9:23
  • I love it - this is right up my alley – Wayne Werner Feb 10 '16 at 16:08
  • Very nice, I like the ASCII – Guillermo Jun 6 '16 at 1:02
13

I've used this one:

countdown()
(
  IFS=:
  set -- $*
  secs=$(( ${1#0} * 3600 + ${2#0} * 60 + ${3#0} ))
  while [ $secs -gt 0 ]
  do
    sleep 1 &
    printf "\r%02d:%02d:%02d" $((secs/3600)) $(( (secs/60)%60)) $((secs%60))
    secs=$(( $secs - 1 ))
    wait
  done
  echo
)

Example:

 countdown "00:07:55"

Here's a source.

  • 2
    POSIX compliant - works on OS X :) – djule5 Feb 24 '15 at 1:02
13
sh-3.2# man leave

set a timer for 15 minutes

sh-3.2# leave +0015
Alarm set for Thu Nov  3 14:19:31 CDT 2016. (pid 94317)
sh-3.2#

edit: I had a bunch of links open, and i thought this was specific to osx, sorry about that. Leaving my answer up so others are aware of leave on the BSDs.

  • 1
    leave works in Linux too, but first you have to install the leave program from the default repositories. – karel Nov 4 '16 at 4:10
6

This is for a stopwatch with hundredths of second:

#!/usr/bin/awk -f
function z() {
  getline < "/proc/uptime"
  close("/proc/uptime")
  return $0
}
BEGIN {
  x = z()
  while (1) {
    y = z()
    printf "%02d:%05.2f\r", (y - x) / 60, (y - x) % 60
  }
}

Example

  • Nice Linux-only solution! I love the lack of external calls. Note, my Debian system has two values in /proc/uptime, with the second presumably referring to my previous uptime. This script can be adjusted to remedy that by changing line 5 to return $1 – Adam Katz Nov 16 '17 at 23:00
4

I have combined the very good terdon's answer, into function which at the same time displays time since start, and time till end. There are also three variants so it's easier to call (you don't have to do bash math), and it's also abstracted. Example of use:

{ ~ }  » time_minutes 15
Counting to 15 minutes
Start at 11:55:34     Will finish at 12:10:34
     Since start: 00:00:08     Till end:  00:14:51

And something like work timer:

{ ~ }  » time_hours 8
Counting to 8 hours
Start at 11:59:35   Will finish at 19:59:35
     Since start: 00:32:41     Till end:  07:27:19

And if you need some very specific time:

{ ~ }  » time_flexible 3:23:00
Counting to 3:23:00 hours
Start at 12:35:11   Will finish at 15:58:11
     Since start: 00:00:14     Till end:  03:22:46

Here's the code to put into your .bashrc

function time_func()
{
   date2=$((`date +%s` + $1));
   date1=`date +%s`;
   date_finish="$(date --date @$(($date2)) +%T )"

   echo "Start at `date +%T`   Will finish at $date_finish"

    while [ "$date2" -ne `date +%s` ]; do
     echo -ne "     Since start: $(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)     Till end:  $(date -u --date @$(($date2 - `date +%s`)) +%H:%M:%S)\r";
     sleep 1
    done

    printf "\nTimer finished!\n"
    play_sound ~/finished.wav
}

function time_seconds()
{
  echo "Counting to $1 seconds"
  time_func $1
}

function time_minutes()
{
  echo "Counting to $1 minutes"
  time_func $1*60
}

function time_hours()
{
  echo "Counting to $1 hours"
  time_func $1*60*60
}

function time_flexible()  # accepts flexible input hh:mm:ss
{
    echo "Counting to $1"
    secs=$(time2seconds $1)
    time_func $secs
}

function play_sound()  # adjust to your system
{
    cat $1 > /dev/dsp
}

function time2seconds() # changes hh:mm:ss to seconds, found on some other stack answer
{ 
    a=( ${1//:/ }) 
    echo $((${a[0]}*3600+${a[1]}*60+${a[2]})) 
}

Combine this with some way of playing sound in linux terminal (play mp3 or wav file via Linux command line) or cygwin (cat /path/foo.wav > /dev/dsp works for me in babun/win7) and you have a simple flexible timer with alarm!

4

Another approach

countdown=60 now=$(date +%s) watch -tpn1 echo '$((now-$(date +%s)+countdown))'

For Mac:

countdown=60 now=$(date +%s) watch -tn1 echo '$((now-$(date +%s)+countdown))'
#no p option on mac for watch

If one wants a signal when it hits zero, one could e.g. build it with a command that returned a non-zero exit status at zero and combine it with watch -b, or something, but if one wants to build a more elaborate script, this is probably not the way to go; it is more of a "quick and dirty one-liner" type solution.


I like the watch program in general. I first saw it after I had already written countless while sleep 5; do loops to different effects. watch was demonstrably nicer.

3

I ended up writing my my own shell script: github gist

#!/bin/sh
# script to create timer in terminal
# Jason Atwood
# 2013/6/22

# start up
echo "starting timer script ..."
sleep 1 # seconds

# get input from user
read -p "Timer for how many minutes?" -e DURATION
DURATION=$(( $DURATION*60 )) # convert minutes to seconds

# get start time
START=$(date +%s)

# infinite loop
while [ -1 ]; do
clear # clear window

# do math
NOW=$(date +%s) # get time now in seconds
DIF=$(( $NOW-$START ))  # compute diff in seconds
ELAPSE=$(( $DURATION-$DIF ))    # compute elapsed time in seconds
MINS=$(( $ELAPSE/60 ))  # convert to minutes... (dumps remainder from division)
SECS=$(( $ELAPSE - ($MINS*60) )) # ... and seconds

# conditional
if [ $MINS == 0 ] && [ $SECS == 0 ] # if mins = 0 and secs = 0 (i.e. if time expired)
then # blink screen
for i in `seq 1 180`; # for i = 1:180 (i.e. 180 seconds)
do
clear # flash on
setterm -term linux -back red -fore white # use setterm to change background color
echo "00:00 " # extra tabs for visibiltiy

sleep 0.5

clear # flash off
setterm -term linux -default # clear setterm changes from above
echo "00:00" # (i.e. go back to white text on black background)
sleep 0.5
done # end for loop
break   # end script

else # else, time is not expired
echo "$MINS:$SECS"  # display time
sleep 1 # sleep 1 second
fi  # end if
done    # end while loop 
  • 1
    Nice script, +1. Just so you know, that is a countdown timer, not a stopwatch. – terdon Jun 25 '13 at 12:17
  • ha you're right, thats what I really wanted. I'll update my naming. – tir38 Jun 26 '13 at 17:31
3

I'm surprised that nobody used the sleepenh tool in their scripts. Instead, the proposed solutions either use a sleep 1 between subsequent timer outputs or a busy loop that outputs as fast as possible. The former is inadequate because due to the small time spent doing the printing, the output will not actually happen once per second but a bit less than that which is suboptimal. After enough time passed, the counter will skip a second. The latter is inadequate because it keeps the CPU busy for no good reason.

The tool that I have in my $PATH looks like this:

#!/bin/sh
if [ $# -eq 0 ]; then
    TIMESTAMP=$(sleepenh 0)
    before=$(date +%s)
    while true; do
        diff=$(($(date +%s) - before))
        printf "%02d:%02d:%02d\r" $((diff/3600)) $(((diff%3600)/60)) $((diff%60))
        TIMESTAMP=$(sleepenh $TIMESTAMP 1.0);
    done
    exit 1 # this should never be reached
fi
echo "counting up to $@"
"$0" &
counterpid=$!
trap "exit" INT TERM
trap "kill 0" EXIT
sleep "$@"
kill $counterpid

The script can either be used as a stop watch (counting up until interrupted) or as a timer that runs for the specified amount of time. Since the sleep command is used, this script allows to specify the duration for which to count in the same precision as your sleep allows. On Debian and derivatives, this includes sub-second sleeps and a nice human-readable way to specify the time. So for example you can say:

$ time countdown 2m 4.6s
countdown 2m 4.6s  0.00s user 0.00s system 0% cpu 2:04.60 total

And as you can see, the command ran exactly for 2 minutes and 4.6 seconds without much magic in the script itself.

EDIT:

The sleepenh tool comes from the package of the same name in Debian and its derivatives like Ubuntu. For distributions that don't have it, it comes from https://github.com/nsc-deb/sleepenh

The advantage of sleepenh is, that it is able to take into account the small delay that accumulates over time from the processing of other things than the sleep during a loop. Even if one would just sleep 1 in a loop 10 times, the overall execution would take a bit more than 10 seconds because of the small overhead that comes from executing sleep and iterating the loop. This error slowly accumulates and would over time make our stopwatch timer more and more imprecise. To fix this problem, one must each loop iteration compute the precise time to sleep which is usually slightly less than a second (for one second interval timers). The sleepenh tool does this for you.

  • I don't understand what benefit this gives over my answer which also uses sleep 0.1. What is sleepnh (I can't find it in the Arch repos) and how does it differ from sleep? As far as I can tell, you're basically doing the same thing as my answer above. What am I missing? – terdon Jan 26 '17 at 12:28
  • @terdon Sleepenh comes from here github.com/nsc-deb/sleepenh The problem with just saying sleep 5 is, that you don't sleep for exactly 5 seconds. Try for example time sleep 5 and you see that running the command takes slightly more than 5 seconds. Over time the errors accumulate. The sleepenh utility allows to easily avoid this accumulation of error. – josch Jan 27 '17 at 8:04
  • OK. On my system I see an error of 0.002 seconds. I really doubt anyone would use this sort of tool and expect better than millisecond accuracy, but it would be better if you at least edit your answer and i) explain why sleepnh is better than sleep (you only say other answers use sleep 1—which they don't, only the OP uses that) and ii) where to get it and how to install it since it isn't a standard tool. – terdon Jan 27 '17 at 13:12
  • 1
    @terdon I explained the difference between sleep and sleepenh in the first paragraph. Anyways, I probably wasn't clear enough on that so I expanded more on that at the end. The millisecond accuracy problems is what you get when calling sleep once. They accumulate over time and at some point it's noticable. I did not say that others only use sleep 1. I said that they use sleep 1 or a busyloop. Which they still do. Show me a counter example. Answers that do sleep 0.1 are the same as those doing sleep 1 except that they accumulate errors even faster. – josch Jan 28 '17 at 6:49
  • I came down the answers looking for someone at least acknowledging the existence of the problem you solved. – mariotomo Feb 20 '18 at 14:11
1

For future reference, there is a command line tool called µTimer with very straightforward command line options for a countdown/count-up timer.

1

Pretend you are a person on OSX looking for a command line stopwatch. Pretend that you don't want to install the gnu tools and just want to run with the unix date

in that case do as @terdon says but with this modification:

function stopwatch(){
    date1=`date +%s`; 
    while true; do 
        echo -ne "$(date -jf "%s" $((`date +%s` - $date1)) +%H:%M:%S)\r"; 
        sleep 0.1
    done
}
  • 1
    I tried it on OS X El Capitan, for some reason it is starting with 16:00:00 – 太極者無極而生 Oct 29 '15 at 2:34
1

Simply use watch + date in UTC time. You can also install some package for big display...

export now="`date +%s -u`";
watch -n 0,1 'date +%T -u -d @$((`date +%s` - $now ))'

#Big plain characters
watch -n 0,1 'date +%T -u -d @$((`date +%s` - $now )) | toilet -f mono12'

#Big empty charaters
watch -n 0,1 'date +%T -u -d @$((`date +%s` - $now )) | figlet -c -f big'

Try it!

See also http://www.cyberciti.biz/faq/create-large-colorful-text-banner-on-screen/

1

sw is a simple stopwatch that will run forever.

sw

Install

wget -q -O - http://git.io/sinister | sh -s -- -u https://raw.githubusercontent.com/coryfklein/sw/master/sw

Usage

sw
 - start a stopwatch from 0, save start time in ~/.sw
sw [-r|--resume]
 - start a stopwatch from the last saved start time (or current time if no last saved start time exists)
 - "-r" stands for --resume
1

A python example:

#!/usr/bin/python

def stopwatch ( atom = .01 ):
    import time, sys, math

    start = time.time()
    last = start
    sleep = atom/2
    fmt = "\r%%.%sfs" % (int(abs(round(math.log(atom,10))))  if atom<1 else "")
    while True:
        curr = time.time()
        subatom = (curr-last)
        if subatom>atom:
            # sys.stdout.write( "\r%.2fs" % (curr-start))
            sys.stdout.write( fmt % (curr-start))
            sys.stdout.flush()
            last = curr
        else:
            time.sleep(atom-subatom)

stopwatch()

demo

0

This is similar to the accepted answer, but terdon's countdown()gave me syntax errors. This one works great for me, though:

function timer() { case "$1" in -s) shift;; *) set $(($1 * 60));; esac; local S=" "; for i in $(seq "$1" -1 1); do echo -ne "$S\r $i\r"; sleep 1; done; echo -e "$S\rTime's up!"; }

You can put it in .bashrc and then execute with: timer t (where t is time in minutes).

0

Found this question earlier today, when looking for a term application to display a large countdown timer for a workshop. None of the suggestions was exactly what I needed, so I quickly put another one together in Go: https://github.com/bnaucler/cdown

As the question is already sufficiently answered, consider this to be for the sake of posterity.

0

$ sleep 1500 && xterm -fg yellow -g 240x80 &

When that big terminal with yellow text jumps up, time to get up and stretch!

Notes: - 1500 seconds = 25 minute pomodoro - 240x80 = terminal size with 240 character row, and 80 rows. Fills up a screen for me noticeably.

Credit: http://www.linuxquestions.org/questions/linux-newbie-8/countdown-timer-for-linux-949463/

0

A GUI version of the stopwatch

date1=`date +%s`
date1_f=`date +%H:%M:%S____%d/%m`
(
  while true; do 
    date2=$(date -u --date @$((`date +%s` - $date1)) +%H:%M:%S)
    echo "# started at $date1_f \n$date2"
  done
) |
zenity --progress \
  --title="Stop Watch" \
  --text="Stop Watch..." \
  --percentage=0
-2

If you would like a compile-able program for whatever reason, the following would work:

#include <iostream>
#include <string>
#include <chrono>

int timer(seconds count) {
  auto t1 = high_resolution_clock::now();
  auto t2 = t1+count;
  while ( t2 > high_resolution_clock::now()) {
    std::cout << "Seconds Left:" <<
    std::endl <<
      duration_cast<duration<double>>(count-(high_resolution_clock::now()-t1)).count() << 
    std::endl << "\033[2A\033[K";
    std::this_thread::sleep_for(milliseconds(100));
  }
  std::cout << "Finished" << std::endl;
  return 0;
}

This can be used in other programs as well and easily ported, if a bash environment isn't available or you just prefer using a compiled program

github

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.