How to edit line alignment and left alignment in Bash

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

Without colors, alignment is ideal, but adding colors leads to incorrect correction of the aligned column in the next row.

#!/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; 
+6
source share
2 answers

I'm not sure why it will transfer to the next line - if non-printable sequences (color changes) should make the line shorter and not longer. A line extension to compensate for the work 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" } 
+6
source

You need to consider 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" } 
+3
source

Source: https://habr.com/ru/post/904770/


All Articles