如何从bash脚本获取彩色输出?


9

当我grep在gnome终端中执行时,我得到彩色输出-容易注意到的匹配,具有不同颜色的行号(-n)等

但是当我grep通过bash脚本执行完全相同的命令时,我得到的是平面输出,而没有着色

有没有一种方法可以通过使用bash脚本获得彩色输出?

Answers:


9

--color当我在外壳程序脚本中运行grep时,使用该选项对我有效。

这是您想要的示例。

grep -n --color=auto "PATTERN" FILE

的确感谢。我浏览了grep手册页,但--color[=WHEN], --colour[=WHEN]感到困惑,尽管解释得很好
zetah 2012年

3

这是一个小脚本,可以帮助您了解tput如何与bash一起使用

#!/bin/bash
#@auth kesavan.muthuvel
#@desc - bash with colors :)

B=`tput bold`           #BOLD
D=`tput dim`            #DIM
U=`tput sgr 0 1`        #UNDERLINE
U2=`tput smul`          #UNDERLINE2
NOU=`tput rmul`         #NO UNDERLINE
H=`tput smso`           #HIGHLIGHT
X=`tput sgr0`           #RESET
C='tput setaf '         #COLOR


for i in 0 1 2 3 4 5 6 7 ; do
        c=`$C$i` && echo $c${B}I${U}always$NOU $D love \
           ${U2}colors$NOU \& $c${H}GNU/Linux$X
done;

这将以BOLD,UNDERLINE,Highlighting和colors 等格式打印以下输出。

具有文本格式和颜色的BASH脚本打印


0

您是否尝试将这些别名添加到您的~/.bashrc

alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'

是的,这些行都存在,但是不幸的是,从bash脚本运行grep时,输出是相同的(没有着色)。
zetah

默认情况下,Shell别名仅对交互式Shell会话有效。您要么需要1)将--color选项添加到grep命令中(显式)(安全),要么2)启用expand_aliasesshell选项和source ~/.bashrc(由于可能存在其他别名而容易出现问题)。您可以优化1)并定义变量GREP="grep --color=auto",然后在脚本$GREPgrep无处不在使用。
David Foerster
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.