Johnbritto
Johnbritto

Reputation: 149

Countdown time bash script without using clear in while loop

With Google reference for countdown time scipt, I'm trying a different output. i.e displaying seconds remaining to proceed: 20. Every time the countdown reaches 10.. it countdown as 90, 80, 70, 60, 50, 40, 30, 20, 10 . There are lot of examples given using clear in while loop, but I don't want to clear my scripts other outputs when displaying the countdown time.

I would like to learn where I am committing a mistake.

function countdown () 
    { 
        if (($# != 1)) || [[ $1 = *[![:digit:]]* ]]; then
            echo "Usage: countdown seconds";
            return;
        fi;
        local t=$1 remaining=$1;
        SECONDS=0;
        while sleep .2; do
            printf '\rseconds remaining to proceed: '"$remaining";
            if (( (remaining=t-SECONDS) <=0 )); then
                printf '\rseconds remaining to proceed' 0;
                break;
            fi;
        done
    }

Upvotes: 3

Views: 2369

Answers (1)

zmccord
zmccord

Reputation: 2612

The problem is that it's actually counting down 9,8,7,6, etc. but you never wiped the trailing 0 from the 10, so it stays on the screen. Easy fix:

printf '\rseconds remaining to proceed: '"$remaining"' ';

Add a space to strike the 0 from the screen and you're all good.

Upvotes: 7

Related Questions