23

I would like to have a count down of 5 minutes, updating every second and showing the result on the same line. Is this even possible with Bash scripting?

closed as unclear what you're asking by Stone, Ward, voretaq7 Aug 21 '13 at 14:02

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • What does the countdown do? You need to be a little more specific about the whole thing. – Adrian Frühwirth Aug 21 '13 at 9:41
  • This is absolutely possible. If you tell us why (what actual system/network administration problem you're trying to solve) we can tell you which of the many available methods to do it will likely work best for you. If it's a general "How do I do this in a bash script?` question your question is probably better suited to Unix & Linux -- let me know and I can migrate it there for you :) – voretaq7 Aug 21 '13 at 14:04
41

This works from Bash shell:

secs=$((5 * 60))
while [ $secs -gt 0 ]; do
   echo -ne "$secs\033[0K\r"
   sleep 1
   : $((secs--))
done

The special character \033[OK represents an end of line which cleans the rest of line if there are any characters left from previous output and \r is a carriage return which moves the cursor to the beginning of the line. There is a nice thread about this feature at stackoverflow.com.

You can add own commands or whatever in the while loop. If you need something more specific please provide me more details.

13

Here's one with an improvement of right output format (HH:MM:SS) with proper leading zeros and supporting hours:

#!/bin/bash

m=${1}-1 # add minus 1 

Floor () {
  DIVIDEND=${1}
  DIVISOR=${2}
  RESULT=$(( ( ${DIVIDEND} - ( ${DIVIDEND} % ${DIVISOR}) )/${DIVISOR} ))
  echo ${RESULT}
}

Timecount(){
        s=${1}
        HOUR=$( Floor ${s} 60/60 )
        s=$((${s}-(60*60*${HOUR})))
        MIN=$( Floor ${s} 60 )
        SEC=$((${s}-60*${MIN}))
     while [ $HOUR -ge 0 ]; do
        while [ $MIN -ge 0 ]; do
                while [ $SEC -ge 0 ]; do
                        printf "%02d:%02d:%02d\033[0K\r" $HOUR $MIN $SEC
                        SEC=$((SEC-1))
                        sleep 1
                done
                SEC=59
                MIN=$((MIN-1))
        done
        MIN=59
        HOUR=$((HOUR-1))
     done
}

Timecount $m

Gives an output that looks like this:

02:04:15
  • The output isn't quite HH:MM:SS. For single digit minutes or seconds, you could see 00:4:5. – chishaku Oct 14 '15 at 14:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.