Bash script count down 5 minutes display on single line [closed]
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?
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[0K 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.
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