pntha
pntha

Reputation: 39

Bash: center and color text with padding either side of a dynamic terminal width using printf

I'm trying to format output using printf to achieve the following:

----------------------------------- HEADING -----------------------------------
-------------------------------- LONGER HEADING -------------------------------

However, my attempts have only resulted in:

- HEADING -
- LONGERHEADING -

My current code looks like:

MAGENTA=$(tput setaf 5)
NOCOL=$(tput sgr0)

heading="${1^^}"
width="$(tput cols)"
padlimit=30
if [[ $width -gt 240 ]]; then
    padlimit="$(( $width/8 ))"
fi
padding="$(printf '%0.1s' -{1..$padlimit})"

printf '%s%*.*s %s %*.*s%s\n' "$MAGENTA" 0 "$(((width-2-${#heading})/2))" "$padding" \
 "$heading" 0 "$(((width-2-${#heading})/2))" "$padding" "$NOCOL"

If I try to hardcode the padding variable's count element, like so:

MAGENTA=$(tput setaf 5)
NOCOL=$(tput sgr0)

heading="${1^^}"
width="$(tput cols)"
padding="$(printf '%0.1s' -{1..60})"

printf '%s%*.*s %s %*.*s%s\n' "$MAGENTA" 0 "$(((width-2-${#heading})/2))" "$padding" \
"$heading" 0 "$(((width-2-${#heading})/2))" "$padding" "$NOCOL"

The results are:

------------------------------ HEADING ------------------------------
------------------------------ LONGER HEADING ------------------------------

I imagine the maths is incorrect in the printf statement. However, I'm unsure as to:

  1. What the arithmetic in the printf statement should be; and
  2. Why, when providing a variable to the padding variable's count element, it doesn't evaluate?

Any help would be appreciated!

Upvotes: 2

Views: 688

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

Just write a for loop and print - in the for loop.

center() {
     local heading width headinglen padlength i
     heading="$*"
     width="$(tput cols)"
     headinglen=${#heading}
     padlength=$(( (width - 2 - headinglen) / 2 ))
     for ((i = 0; i < padlength; ++i)); do
        printf "-"
     done
     printf " %s " "$heading"
     for ((i = 0; i < padlength; ++i)); do
          printf "-"
     done
     if (( (width - 2 - headinglen) % 2 )); then
          printf "-"
     fi
     printf "\n"
}
center HEADING
center LONGER HEADING

Upvotes: 2

Related Questions