How can I print a variable with padded center alignment?

I found two pieces of information here on the stackexchange network that helped me arrive at this working answer:

  • https://stackoverflow.com/q/263890/5419599
  • https://stackoverflow.com/q/4409399/5419599

However the code in this answer is my own.

See the edit history if you want more verbosity; I've edited out all the cruft and "steps along the way."


I think the best way is:

center() {
  termwidth="$(tput cols)"
  padding="$(printf '%0.1s' ={1..500})"
  printf '%*.*s %s %*.*s\n' 0 "$(((termwidth-2-${#1})/2))" "$padding" "$1" 0 "$(((termwidth-1-${#1})/2))" "$padding"
}
center "Something I want to print"

Output on a terminal 80 columns wide:

========================== Something I want to print ===========================

Note that the padding doesn't have to be a single character; in fact the padding variable isn't, it's 500 characters long in the above code. You could use some other form of padding by changing just the padding line:

padding="$(printf '%0.2s' ^v{1..500})"

Results in:

^v^v^v^v^v^v^v^v^v^v^v^v^v Something I want to print ^v^v^v^v^v^v^v^v^v^v^v^v^v^

Another handy use is:

clear && center "This is my header"