Highway of Life
Highway of Life

Reputation: 24321

How to right align and left align text strings in Bash

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;

Upvotes: 6

Views: 11355

Answers (2)

chrisaycock
chrisaycock

Reputation: 37930

You have to account for the extra space provided by the colors.

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

    echo -n $MSG
    printf "%${COL}s\n"  "$STATUSCOLOR"
}

Upvotes: 3

Gordon Davisson
Gordon Davisson

Reputation: 125768

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"
}

Upvotes: 7

Related Questions