如何设置带有颜色的变量并与 bash 左对齐

How to set a variable with color and left align with bash

如何设置带有颜色的变量并与 bash

左对齐

示例:

red=$(tput setaf 1)
green=$(tput setaf 2)
normal=$(tput sgr0)


if [ $process_state != "running" ]; then
    process_state=${red}$process_state${normal}
else
    process_state=${green}$process_state${normal}
fi

printf "%-10s|" $process_state

输入

process_state=running
process_state=stopped

输出

running   | <-- Where this is in green
stopped   | <-- Where this is in red

*** 已更新 *** 解决方案:

red=$(tput setaf 1)
green=$(tput setaf 2)
normal=$(tput sgr0)


if [ $process_state != "running" ]; then
    process_state="${red} $process_state ${normal}"
else
    process_state="${green} $process_state ${normal}"
fi

printf "%s%-10s%s|" $process_state

注意:注意 $process_state 周围的空格将它与颜色分开。

按照您的方式计算字段宽度会出现问题,因为 $red$green 没有 printf 的零宽度。

我会用下一种方式重新编码:

red=$(tput setaf 1)
green=$(tput setaf 2)
normal=$(tput sgr0)

if [ "$process_state" != "running" ]; then
    printf "%s%-10s%s|" "$red" "$process_state" "$normal"
else
    printf "%s%-10s%s|" "$green" "$process_state" "$normal"
fi