# Text centering function in bash

I wanted to center some text in my commandline application, so I came up with this function.

centerText(){
textsize=${#1} spacecount=$(tput cols)
spacecount=$((($spacecount-$textsize)/2)) while [$spacecount -gt 0 ]
do
printf " "
spacecount=$((spacecount-1)) done printf "$1"
echo
}


If you have suggestions on how to improve the code, and/or know a better way of centering text, please let me know.

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. • So using printf "%7s" "TEST" it would output " TEST" (3 spaces)? – insanikov Jun 24 '15 at 11:27 • That's right. I should have included a link... Here the printf man page – rolfl Jun 24 '15 at 11:34 • I see, I had already googled but only looked at printf(1) and not printf(3), my apologies. – insanikov Jun 24 '15 at 11:37 • No problem. Printf formatting is complicated to learn, but well worth it for many languages, C, C++, Java, etc. and then reused in other places like bash. It is worth understanding it. – rolfl Jun 24 '15 at 11:41 You can make your script more readable by using proper indentation and spacing. All commands inside the function block {} should be indented one level (for clarity). Consider putting spaces around the arithmetic operators too: $((($spacecount -$textsize) / 2)). I find this style much easier to read and understand quickly.