[英]How to colorize command output in bash script?
I'am trying few days to change color output from command in bash script. 我正在尝试几天来更改bash脚本中命令的颜色输出。 I tried some workflows with eg trap but without success.The only what partially working is this code:
我尝试了一些工作流程,例如使用陷阱,但没有成功。唯一可以部分工作的代码是:
#!/bin/bash
GRN='\e[32m'
CYN='\e[36m'
END='\e[0m'
echo -e "${GRN}Formating 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 "${GRN}Formating Home partition ..${END}"
...
Is there some better way how to do it. 是否有一些更好的方法来做到这一点。 Thank you.
谢谢。
What I want is this: 我想要的是:
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
You can use the below script, tested on mac and ubuntu. 您可以使用在Mac和ubuntu上经过测试的以下脚本。
each function accept two-argument, 每个函数接受两个参数,
green "will print green"
green "will print green"
red "will print Free space in red:" "free -m" free -m
red "will print Free space in red:" "free -m" free -m
bash script 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") "
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.