Since you are using printf to output the spaces, you may as well use a specific printf format for the output.
Here's a replacement function:
centerQ(){
textsize=${#1}
width=$(tput cols)
span=$((($width + $textsize) / 2))
printf "%${span}s\n" "$1"
}
What it does is it identifies how long the whole output should be, by adding the text width and screen width together, then dividing by 2. That's a bit complicated to explain, but, the right-side of the text must be half-as-much-of-the-text as the middle of the screen.
For example, if the text is 10 characters, and the screen is 80, then the right side of the output must be at 45, or (10 + 80) / 2
If we know the right-hand side of the output, you can just make that a real printf statement:
printf "%45s" "some text!"
The function above does that, by using the padded %s
format, it left-pads the output to 45 characters overall width.
By adding the newline escape \n
to the printf you save the echo
too.