如何在 bash 脚本中为命令输出着色?

Posted

技术标签:

【中文标题】如何在 bash 脚本中为命令输出着色?【英文标题】:How to colorize command output in bash script? 【发布时间】:2019-11-27 06:14:56 【问题描述】:

我正在尝试几天来更改 bash 脚本中命令的颜色输出。我尝试了一些工作流程,例如陷阱但没有成功。唯一部分工作的是这段代码:

#!/bin/bash

GRN='\e[32m'
CYN='\e[36m'
END='\e[0m'

echo -e "$GRNFormating Root partition ..$END"

echo -e "$CYN"
(set -x ; mkfs.ext4 -L Root -m 5 /dev/sda2) | GREP_COLOR='49;38;5;007' grep --color=always '.*' 
echo -e "$END"

echo -e "$GRNFormating Home partition ..$END"

...

有没有更好的方法来做到这一点。谢谢。

我想要的是这个:

Formating Root partition ..                                    <= Green
mkfs.ext4 -L Root -m 5 /dev/sda2                               <= Cyan
mke2fs 1.45.2 (27-May-2019)                                    <= Grey
Creating filesystem with 9175040 4k blocks and 2293760 inodes  <= Grey
Filesystem UUID: ...                                           <= Grey
...                                                            <= Grey
Formating Home partition ..                                    <= Green

【问题讨论】:

我认为这个帖子可能会对你有所帮助:***.com/a/20983251/3433923 【参考方案1】:

您可以使用以下脚本,在 mac 和 ubuntu 上测试。

每个函数接受两个参数,

    用于示例字符串输出,例如green "will print green" 打印命令输出例如red "will print Free space in red:" "free -m" free -m

bash 脚本

#!/bin/bash
set +x
function black()
    echo -e "\x1B[30m $1 \x1B[0m"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[30m $($2) \x1B[0m"
    fi

function red()
    echo -e "\x1B[31m $1 \x1B[0m"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[31m $($2) \x1B[0m"
    fi

function green()
    echo -e "\x1B[32m $1 \x1B[0m"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[32m $($2) \x1B[0m"
    fi

function yellow()
    echo -e "\x1B[33m $1 \x1B[0m"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[33m $($2) \x1B[0m"
    fi

function blue()
    echo -e "\x1B[34m $1 \x1B[0m"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[34m $($2) \x1B[0m"
    fi

function purple()
    echo -e "\x1B[35m $1 \x1B[0m \c"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[35m $($2) \x1B[0m"
    fi

function cyan()
    echo -e "\x1B[36m $1 \x1B[0m"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[36m $($2) \x1B[0m"
    fi

function white()

    echo -e "\x1B[37m $1 \x1B[0m"
    if [ ! -z "$2" ]; then
    echo -e "\x1B[33m $($2) \x1B[0m"
    fi



green "Green: Formating Root partition .."
white "White: Formating Root partition .."
# pass the second parameter, will be treated as command
yellow "color command output,print ls:" "ls"
red "Red: System Free RAM:" "free -m"
cyan "cyan: awesome..........end..................."
echo -e "mix the color $(purple "Purple: this is purple, will print disk usage" "du -h") Now Yellow: $(yellow "hi Yelow") "

【讨论】:

以上是关于如何在 bash 脚本中为命令输出着色?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Ruby 脚本中为命令 shell 获取环境变量?

如何从 bash 获取 telnet 命令的输出?

如何在 Linux 中为每个输出行列出一个文件名?

为 PHP 的 Windows 命令行输出着色

如何从输出到前景的Bash脚本运行无限循环

在 bash 脚本中为 ssh 命令提供密码,无需使用公钥和 Expect