Linux Terminal Clock

Ever wanted to have a real-time clock on your linux terminal? We can create one with a single line of bash, like so:

while echo -en "$(date)\r"; do sleep 1; done

Let’s look at how this works:

  • date is a common unix tool used to print the current date and time. The $(...) means that the date command is run, and the output is placed here instead. For example, if logged in as root, echo "I am $(whoami)!" is the same as echo "I am root!".
  • echo -en will print the output of $(date). -e allows escaped characters (the \r in this case), and -n means echo will not add a newline character to the end of the line.
  • \r is a carriage return character. This returns the cursor to the beginning of the current line, which means the next thing to print will overwrite anything on that line.
  • while <condition>; do <commands>; done is a standard while loop; <commands> will be run while <condition> returns true (ie: execution is successful).
  • sleep 1 will pause program execution for 1 second.

Altogether, it means we will print the date every second, overwriting the previously printed date, until we end the program (ctrl-c) or until the echo command fails (which is unlikely to happen).

Leave a Reply

Your email address will not be published.