user556068 user556068 - 1 year ago 66
Bash Question

Display date and time like a digital clock in Bash

The command

date +'%a %b %e %Y%n%I:%M %p'
displays the date and time in the format:

Thu Sep 22 2016
08:02 PM

I was trying to think of a way to have the date and time update as the time changes. The only thing I can think of would be to do something like this:


while true
date +'%a %b %e %Y%n%I:%M %p'
done | awk '!seen[$0]++'

This produces output like:

Thu Sep 22 2016
08:02 PM
08:03 PM
08:04 PM

Is there a way to display the time change by overwriting the old time so that
changes to
on the same line, essentially making the date and time display like a regular digital clock?

Answer Source

To update the first line only when the day changes, and the second line every second:

while :; do
  # store start date in variable
  printf -v start_day '%(%a %b %e %Y)T'

  echo "$day"
  while sleep 1 && [[ $start_day = $day ]]; do
      printf -v day '%(%a %b %e %Y)T'
      printf '\r%(%I:%M %p)T'

Using printf %()T restricts compatibility to recent bash 4.x, but substantially improves performance (avoiding the need to start an external program every time we want to update the time).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download