Skip to content

Center Text on the Terminal

Print a line padded with spaces so the text sits in the middle of the current terminal width, using tput for the column count.

Language: Shell

Added on: 18th August 2026

center_text() {
  textsize=${#1}
  span=$(((screen_width + textsize) / 2))

  printf '%*s\n' "${span}" "$1"
}

get_screen_width() {
  screen_width=$(tput cols)
  declare -g screen_width
}

Caveats

Call get_screen_width first, or set screen_width yourself. Requires tput.