1

我有一些日志语法。例如,如果我遇到错误,我会得到如下信息:

[ERROR] You get error here

我如何拦截终端(例如 ubuntu)并为该文本着色?

4

1 回答 1

1

你可以这样做:

## Color coded message
ERR=$(printf "%-25s" "$(echo -e "\033[1;31m[ ERROR ]\033[0m")")
OKY=$(printf "%-25s" "$(echo -e "\033[1;32m[  OK   ]\033[0m")")
WRN=$(printf "%-25s" "$(echo -e "\033[1;33m[ WARN  ]\033[0m")")
INF=$(printf "%-25s" "$(echo -e "\033[1;36m[ INFO  ]\033[0m")")

echo -e "${ERR}You get error here!!"
echo -e "${OKY}This is a success!!"
echo -e "${WRN}You have been warned!!"

希望能帮助到你。干杯!!


wrt你的第二个问题,改变这样的代码为整行着色:

ER="\033[0;31m"
OK="\033[0;32m"
WR="\033[0;33m"
IN="\033[0;34m"
NC="\033[0m"
#
echo -e "${ER}[ERROR] You get Error here!!${NC}"
echo -e "${OK}[OKAY ] This is a Success!!${NC}"
echo -e "${WR}[WARN ] You have been Warned!!${NC}"
echo -e "${IN}[INFO ] You have been Informed!!${NC}"

或者,创建一个类似这样的函数():

function txtColor()
{
    local typ="$1"
    local msg="${@:2}"

    if [ $typ == "ER" ]; then
        echo -e "\033[0;31m[ ERROR ]  ${msg}\033[0m"
    elif [ $typ == "OK" ]; then
        echo -e "\033[0;32m[ OKAY  ]  ${msg}\033[0m"
    elif [ $typ == "WR" ]; then
        echo -e "\033[0;33m[ WARN  ]  ${msg}\033[0m"
    elif [ $typ == "IN" ]; then
        echo -e "\033[0;34m[ INFO  ]  ${msg}\033[0m"
    else
        echo -en "\033[1;33m[ WARN  ]  Wrong message type: "
        echo -e "${typ}\033[0m\n\t   ${msg}"
    fi
}

并在您喜欢的任何地方使用它:

txtColor "ER" You got Error here!! 
txtColor OK "This is a success!!"
txtColor "WR" "You have been warned!!" 
txtColor OL Text without any color!!

(根据需要更改间距 ans.or 类型)仅供参考,如果您想要粗体文本,请将其全部0;替换。1;干杯!!

于 2013-10-25T18:49:50.157 回答