While creating a countdown timer in bash, I came up with the following code:
for ((n=15; n > 0; n--)); do
printf "Reload | $n" && sleep 1
done
This works fine, it keeps adding the printf
to the same line, as expected.
So I opened the documentation on tput
and found:
tput el1
Clear to beginning of line
And tried it out:
for ((n=15; n > 0; n--)); do
tput el1; printf "Reload | $n" && sleep 1
done
However, this adds a tab on each iteration, so the output becomes:
Reload | 15
Reload | 14
Reload | 13
Those outputs are on the same line, so the 'clear' works but for some reason is the cursor not restored to the first column.
I've managed to fix it by adding a carriage return (\r
) behind the printf
:
for ((n=15; n > 0; n--)); do
tput el1; printf "Reload | $n\r" && sleep 1
done
I've read quite some docs, but can't grasp why the \r
is needed here. Please point me to the right documentation/duplicate about this matter.