For a bash timer i use this code:
#!/bin/bash
sek=60
echo "60 Seconds Wait!"
echo -n "One Moment please "
while [ $sek -ge 1 ]
do
echo -n "$sek "
sleep 1
sek=$[$sek-1]
done
echo
echo "ready!"
That gives me something like that
One Moment please: 60 59 58 57 56 55 ...
Is there a possibility to replace the last value of second by the most recent so that the output doesn't generate a large trail but the seconds countdown like a real time at one position? (Hope you understand what i mean :))
Basically the same as aneeshep's answer, but uses Return (
\r
) rather than Backspace (\b
) because we don't know if the length will always be the same, e.g. when$sek < 10
.Also, your first
echo
should use$sek
, not hard-code60
.Finally, note the space after the
...
.With bash you can use the special variable
SECONDS
.In addition to
\r
or\b
approaches, it's possible to use the\033[2K
control character, which tells the terminal to clear the whole line. The advantage of this compared to\b
is that you don't have to match number of\b
with the amount of characters you want to delete, and compared to\r
there won't be characters sticking out on the screen if the new line is shorter than the old one.Below is the example of how it can be applied to this question, and here is an example of the related application to create output similar to boot messages. In this particular example, the timer will be gone once 0th second is reached and the timer line will be replaced with "Ready!" phrase.
Another alternative would be to employ
dialog
command for creating simple dialogs in command-line. The dialog will remain on screen for the duration of the timer and update with the loop, and by the time it's done - the timer will be replaced with "Ready! Press to exit" message in a seamless manner:This is what I came up with after reading here and a bit more, the one liner:
More readable:
Where SEC can be set to whatever positive integer and the printf will take care of appropriate padding. Tested under Ubuntu and cygwin.
Can achieve it by placing carriage return
\r
.In a single line of code, it is possible with
echo -ne
or with
printf
Countdown timer:
and the 'normal' stopwatch is:
control+c to stop