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

spacecount=$(tput cols)
while [ $spacecount -gt 0 ]
        printf " "
printf "$1"

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


2 Answers 2


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:

  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.

  • \$\begingroup\$ So using printf "%7s" "TEST" it would output " TEST" (3 spaces)? \$\endgroup\$
    – insanikov
    Jun 24, 2015 at 11:27
  • \$\begingroup\$ That's right. I should have included a link... Here the printf man page \$\endgroup\$
    – rolfl
    Jun 24, 2015 at 11:34
  • \$\begingroup\$ I see, I had already googled but only looked at printf(1) and not printf(3), my apologies. \$\endgroup\$
    – insanikov
    Jun 24, 2015 at 11:37
  • \$\begingroup\$ 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. \$\endgroup\$
    – rolfl
    Jun 24, 2015 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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.