user556068 user556068 - 2 months ago 16
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:

#!/bin/bash

while true
do
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
08:02
changes to
08:03
on the same line, essentially making the date and time display like a regular digital clock?

Answer

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'
  day=$start_day

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

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).

Comments