How to overwrite an echo/printf line with another one? (Making it start at the center of the screen)

I want to write a script which outputs sentences I choose. I want them to appear in the center of the screen: output the first one, and then make the second one appear over the first. Here’s my code:

    COLUMNS=$(tput cols) 

printf "%*s\n" $((($COLUMNS)/2)) "Hey, welcome to my script!" "%\r"
sleep 2
printf "%*s" $((($COLUMNS)/2)) "This is a new line!"

My intention is to overwrite the first line with the second, in the same way as telnet towel.blinkenlights.nl does at the beginning of their particular Star Wars version. I managed to make them appear at the center by reading another question, but I find impossible to make the second line start at the very same line of the first. Any clues?

Answer

The problem is that you have a \n in your first printf. That makes the cursor move to the next line, so when you print the new text it is not on the same line to overwrite the old text. If you remove that you should be good:

COLUMNS=$(tput cols) 

printf "%*s\r" $((COLUMNS/2)) "Hey, welcome to my script!"
sleep 2
printf "%*s" $((COLUMNS/2)) "This is a new line!"
printf "\n"

I fixed up your correct observation about the \r being wrong, and simplified the math a little. Then I added a last \n to get the prompt onto its own line at the end

Attribution
Source : Link , Question Author : xvlaze , Answer Author : Eric Renouf

Leave a Comment