Creating A Terminal Window Clock

January 10, 2012 by
Filed under: bash, command line, HowTo, linux 

If you've been using Linux for a while, you may be familiar with the terminal command, date. The date command will display the current date and time to the terminal. On my system, the default output of date looks like this:

Tue Jan 10 23:23:21 EST 2012

The output can be adjusted with command line switches to show only the current time. The time will be output in the format of the system locale by using the +%r switch, so the command will look like this:

date +%r

Which gives the following output on my system:

11:23:22 PM

So now that I can display the current time, I just need to figure out how to continuously update the information in order to create a terminal clock. I'm going to do that by using the echo command to display the output of the date command. By using some options with echo so that the output gets over-written, and placing that command in an infinite loop, I can display a simple clock in the terminal.

Affiliate Link

So here's the command:

clear; while true; do echo -e \\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b`date +%r` \\c ; sleep 1; done

Take note of the back-ticks around the date command. That tells the echo command to display the results of the date command. The "\\b" enters a backspace into the command and "\\c" tells echo not to enter a newline character. The number of \\b's needed will depend on the output time display format for your locale, so adjust this up or down as needed.

All in all, it's not that useful as most GUI based systems have a clock build in, but it provides a nice example of using an infinite loop as well as some of the special options available with the echo and date commands.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>