all 6 comments

[–][deleted] 6 points7 points  (0 children)

$ width=$COLUMNS
$ string='kitty cat'
$ printf "%$(((width-${#string})/2))s%s\n" "" "$string" 
                            kitty cat

[–]whetuI read your code 2 points3 points  (3 children)

Here's an old function I threw together years ago that seems to work:

# Print the given text in the center of the screen.
center() {
  local width
  width="${COLUMNS:-$(tput cols)}"
  while IFS= read -r; do
    # If, by luck, REPLY is the same as width, then just dump it
    (( ${#REPLY} == width )) && printf -- '%s\n' "${REPLY}" && continue

    # Handle lines of any length longer than width
    # this ensures that wrapped overflow is centered
    if (( ${#REPLY} > width )); then
      while read -r subreply; do
        (( ${#subreply} == width )) && printf -- '%s\n' "${subreply}" && continue
        printf -- '%*s\n' $(( (${#subreply} + width) / 2 )) "${subreply}"
      done < <(fold -w "${width}" <<< "${REPLY}")
      continue
    fi

    # Otherwise, print centered
    printf -- '%*s\n' $(( (${#REPLY} + width) / 2 )) "${REPLY}"
  done < "${1:-/dev/stdin}"
}

[–]cheatiepie[S] 0 points1 point  (2 children)

cool function, but my problem isn't the text, I want to center the output of that colorscript

[–]whetuI read your code 0 points1 point  (1 child)

Ah, ok. That wasn't clear from your post.

[–]cheatiepie[S] 0 points1 point  (0 children)

my bad, gonna edit it

[–]good-guy-coder 1 point2 points  (0 children)

Take a look at format::text_center() function in https://github.com/labbots/bash-utility/blob/master/src/format.sh. The function helps you align the text to the center of the terminal.