Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 202
Highway of Life Avatar asked Dec 30 '11 18:12

Highway of Life


2 Answers

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"
}
like image 81
Gordon Davisson Avatar answered Oct 23 '22 04:10

Gordon Davisson


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"
}
like image 41
chrisaycock Avatar answered Oct 23 '22 03:10

chrisaycock