[英]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. 我正在创建一个bash脚本,并希望在同一行显示一个具有正确对齐状态(OK,Warning,Error等)的消息。
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;
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): 加宽线以补偿我的工作(BTW我建议使用printf而不是
echo -n
作为实际消息):
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"
}
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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.