Thursday, May 16, 2013

Countdown Clock/Timer in /bin/bash

Often there is a need to have time between batch jobs. Knowing how much time there is between jobs is useful.

Here are two version.
  1. One I found on unix.com here by cfajohnson. He claims it will work in any POSIX shell
  2. The other I (tc) wrote.

Version #1

# by cfajohnson
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
)

countdown "00:07:55"

Version #2 


# by teacup
countSecondsDown()
{
  seconds=$1
  while [ $seconds -ge 0 ]
  do
    # you need the ampersand after sleep if you use wait.
    # because wait will wait for child process of sleep to complete.
    sleep 1 &
    printf "\r%d  " $seconds
    seconds=$(( $seconds - 1 ))
    wait
  done
  echo

}

countSecondsDown 71
 

No comments: