How to right align and left align text strings in Bash

Highway of Life picture Highway of Life · Dec 30, 2011 · Viewed 9.8k times · Source

I'm creating a bash script and would like to display a message with a right aligned status (OK, Warning, Error, etc) on the same line.

Without the colors, the alignment is perfect, but adding in the colors makes the right aligned column wrap to the next line, incorrectly.

#!/bin/bash

log_msg() {
    RED=$(tput setaf 1)
    GREEN=$(tput setaf 2)
    NORMAL=$(tput sgr0)
    MSG="$1"
    let COL=$(tput cols)-${#MSG}

    echo -n $MSG
    printf "%${COL}s"  "$GREEN[OK]$NORMAL"
}

log_msg "Hello World"
exit;

Answer

Gordon Davisson picture Gordon Davisson · Dec 30, 2011

I'm not sure why it'd wrap to the next line -- having nonprinting sequences (the color changes) should make the line shorter, not longer. Widening the line to compensate works for me (and BTW I recommend using printf instead of echo -n for the actual message):

log_msg() {
    RED=$(tput setaf 1)
    GREEN=$(tput setaf 2)
    NORMAL=$(tput sgr0)
    MSG="$1"
    let COL=$(tput cols)-${#MSG}+${#GREEN}+${#NORMAL}

    printf "%s%${COL}s" "$MSG" "$GREEN[OK]$NORMAL"
}