Please how can i display a 60 second active countdown timer in an echo message.
e.g.
#!/bin/ksh
for (( i=60; i>0; i--)); do
sleep 1 &
printf " $i \r"
wait
done
This work in ksh as well. For posix you probably have to use a while loop.
Hi
this is not the best solution, but you can improve it.
input=60
tic=`date +%S`
elap_time=0
while [ "$elap_time" -le "$input" ]; do
toc=`date +%S`
elap_time=`expr $toc - $tic`
done
echo "time elapsed"
EDIT: Sorry I don't answ to your question, becouse you want display it.
Bye
Works (almost) fine in bash, too. But I don't understand the use of the sleep command as a background process. Furthermore, the "done" messages caused by returning sleeps disturb the display
Nevertheless, much simplier would be just the good ole
sleep 60; echo "\a"
BR,
pen
countdown()
{
countdown=${1:-60} ## 60-second default
w=${#countdown}
while [ $countdown -gt 0 ]
do
sleep 1 &
printf " %${w}d\r" "$countdown"
countdown=$(( $countdown - 1 ))
wait
done
printf "\a"
} 2>/dev/null
Hi Pen, the sleep in the background ensures that you use as little time as possible processing the other commands in the loop. Otherwise total sleep is sometimes a bit more than 60 seconds.
You'll get done messages if you execute it from the command line, not if you execute it from a script. Alternatively you can enclose it in parentheses like so:
(for (( i=60; i>0; i--)); do
sleep 1 &
printf " $i \r"
wait
done)
Then you won't get the pesky job status.
Or you can put it in a function like CFA suggests..
(BTW I just changed the \b\b for \r because now I realise the backspaces weren't working properly).
Indeed, but it is my understanding that the OP requested a countdown timer.
i=60;while [ $i -gt 0 ];do if [ $i -gt 9 ];then printf "\b\b$i";else printf "\b\b $i";fi;sleep 1;i=`expr $i - 1`;done
(Code reformatted for legibility.)
That loop will take noticably longer than one second, due partly to the unnecessary external command.