Search code examples
bashsleeppv

Making countdown bar with pv


Following this 2013 question, on displaying a countdown in a terminal, I would like to improve the answer a bit using pv to show a progression bar.

Here is my current script.

function countdown {
   date1=$((`date +%s` + $1));
   while [ "$date1" -ge `date +%s` ]; do
     echo -ne "$(date -u --date @$(($date1 - `date +%s`)) +%H:%M:%S)\r";
     sleep 0.1
   done
}

# 7 minutes countdown
countdown $((7*60))

How do I improve this with pv? It looks like it tracks progress measuring data written. In my case I just need to wait and I don't have indicators to measure.

Maybe there are best alternatives as of 2018?

Thanks.


Solution

  • Just do it this way with pv, writing one Byte of character every second.

    secs=$((7 * 60))
    while [ $secs -gt 0 ]
    do 
      echo -n "."
      sleep 1
      : $((secs--))
    done | pv -s $secs > /dev/null
    

    echo -n is for

      -n     do not output the trailing newline
    

    pv -s is for

      -s, --size SIZE          set estimated data size to SIZE bytes
    

    sleep 1; : $((secs--)) to decrement the value of $secs every 1 second