为您的终端和 shell 环境着色?

Ste*_*ski 284 shell colors bash prompt

我大部分时间都在 Unix 环境中工作并使用终端模拟器。我尝试在命令行上使用颜色,因为颜色使输出更加有用和直观。

有哪些选项可以为我的终端环境添加颜色?你用什么技巧?你遇到过哪些陷阱?

不幸的是,对颜色的支持因终端类型、操作系统、TERM 设置、实用程序、错误实现等而异。

经过大量实验,以下是我的设置中的一些提示:

  1. 我倾向于设置TERM=xterm-color,大多数主机(但不是全部)都支持。
  2. 我在许多不同的主机、不同的操作系统版本等上工作。我使用 macOS?X、Ubuntu Linux、RHEL/CentOS/Scientific Linux 和 FreeBSD 中的所有内容。如果可能的话,我试图让事情保持简单和通用。
  3. 我使用 GNU 做了很多工作screen,这增加了另一层乐趣。
  4. 许多操作系统dircolors默认设置类似和,我不想在一百个不同的主机上修改它。所以我尝试坚持使用默认值。相反,我调整了终端的颜色配置。
  5. 对某些Unix 命令ls, grep, less, vim)和Bash 提示符使用颜色。这些命令似乎使用标准的“ ANSI 转义序列”。例如:

    alias less='less --RAW-CONTROL-CHARS'
    export LS_OPTS='--color=auto'
    alias ls='ls ${LS_OPTS}'
    
    Run Code Online (Sandbox Code Playgroud)

我会发布我的.bashrc并回答我自己的问题 Jeopardy Style。

Luc*_*nes 139

您可以执行以下操作:

编辑器 + 代码
很多编辑器都有语法高亮支持。vimemacs默认开启。您也可以在 下启用它nano

您还可以使用Pygments作为命令行工具在终端上使用语法高亮代码。

grep
grep --color=auto突出显示所有匹配项。您还可以使用export GREP_OPTIONS='--color=auto'它在没有别名的情况下使其持久化。如果您使用--color=always,它会在管道时使用颜色,这会使事情变得混乱。

ls

ls --color=always

指定颜色:

export LS_COLORS='rs=0:di=01;34:ln=01;36:mh=00:pi=40;33'
Run Code Online (Sandbox Code Playgroud)

(提示:dircolors可能会有所帮助)

PS1
您可以将 PS1(shell 提示)设置为使用颜色。例如:

PS1='\e[33;1m\u@\h: \e[31m\W\e[0m\$ '
Run Code Online (Sandbox Code Playgroud)

将产生一个 PS1,如:

[黄色]lucas@ubuntu:[红色]~[正常]$

你可以通过这个获得真正的创意。作为一个想法:

PS1='\e[s\e[0;0H\e[1;33m\h    \t\n\e[1;32mThis is my computer\e[u[\u@\h:  \w]\$ '
Run Code Online (Sandbox Code Playgroud)

在终端顶部放置一个带有一些随机信息的栏。(为了获得最佳效果,还可以使用alias clear="echo -e '\e[2J\n\n'"。)

摆脱转义序列

如果某些东西在您不希望输出颜色时卡住了,我使用这一sed行来去除转义序列:

sed "s/\[^[[0-9;]*[a-zA-Z]//gi"
Run Code Online (Sandbox Code Playgroud)

如果你想要更真实的体验,你也可以去掉以 开头的行\e[8m,它指示终端隐藏文本。(没有得到广泛支持。)

sed "s/^\[^[8m.*$//gi"
Run Code Online (Sandbox Code Playgroud)

还要注意那些 ^[s 应该是实际的,文字 ^[s。您可以通过在 bash 中按 ^V^[ 来输入它们,即Ctrl+ V, Ctrl+ [

  • 转义符应包含在 `\[...\]` 中,否则第二行中的命令将覆盖第一行。PS1='\[\e[33;1m\]\u@\h: \[\e[31m\]\W\e[0m\$' (6认同)

小智 98

我也用:

export TERM=xterm-color
export GREP_OPTIONS='--color=auto' GREP_COLOR='1;32'
export CLICOLOR=1
export LSCOLORS=ExFxCxDxBxegedabagacad
Run Code Online (Sandbox Code Playgroud)

如果您喜欢为提示着色,定义的颜色变量可能很有用:

export COLOR_NC='\e[0m' # No Color
export COLOR_BLACK='\e[0;30m'
export COLOR_GRAY='\e[1;30m'
export COLOR_RED='\e[0;31m'
export COLOR_LIGHT_RED='\e[1;31m'
export COLOR_GREEN='\e[0;32m'
export COLOR_LIGHT_GREEN='\e[1;32m'
export COLOR_BROWN='\e[0;33m'
export COLOR_YELLOW='\e[1;33m'
export COLOR_BLUE='\e[0;34m'
export COLOR_LIGHT_BLUE='\e[1;34m'
export COLOR_PURPLE='\e[0;35m'
export COLOR_LIGHT_PURPLE='\e[1;35m'
export COLOR_CYAN='\e[0;36m'
export COLOR_LIGHT_CYAN='\e[1;36m'
export COLOR_LIGHT_GRAY='\e[0;37m'
export COLOR_WHITE='\e[1;37m'
Run Code Online (Sandbox Code Playgroud)

然后我的提示是这样的:

case $TERM in
     xterm*|rxvt*)
         local TITLEBAR='\[\033]0;\u ${NEW_PWD}\007\]'
          ;;
     *)
         local TITLEBAR=""
          ;;
    esac

local UC=$COLOR_WHITE               # user's color
[ $UID -eq "0" ] && UC=$COLOR_RED   # root's color

PS1="$TITLEBAR\n\[${UC}\]\u \[${COLOR_LIGHT_BLUE}\]\${PWD} \[${COLOR_BLACK}\]\$(vcprompt) \n\[${COLOR_LIGHT_GREEN}\]?\[${COLOR_NC}\] "  
Run Code Online (Sandbox Code Playgroud)

$(vcprompt) 在我的 ~/sbin 中调用 python 脚本,它打印有关当前路径的版本控制信息。它包括对 Mercurial、Git、Svn、Cvs 等的支持,脚本作者在这里源码

Bash 提示截图

这是我的提示配置的完整来源


小智 19

grepls已经提到,如果你想有更多颜色看看通用Coloriser,其最初目的是上色的日志文件,但它也colorizes框的右出pingtraceroutegccmakenetstatdifflastldap,和cvs

如果您知道正则表达式,它很容易扩展。我已将ps和添加nmap到列表中(如果您进入,grc我将非常乐意分享这两个工具的 .conf 文件)

(顺便说一句,通过 , 等方式安装它synapticpacman您可能会更幸运地搜索“grc”)


Mic*_*ant 14

多年来,我已经磨练了我的 .bashrc 以在 OSX 和 Ubuntu 上工作。
我还使用紧凑的条件语句将其大小减少到 28 行。
有了它,我的 PS1 提示看起来像: 在此处输入图片说明

时间为红色,用户名为绿色,机器名称为浅蓝色,密码为深蓝色,git branch 为黄色。

我的 PS1 提示功能:

  • 显示 git 分支!
  • 长目录路径(超过 6 个元素)被“修剪”以显示顶部 3 和底部 3 个目录,_然后(这pwd sed是 LOCATION的一部分)。
  • 最后回车,提示总是在左边!

我的.bashrc文件中的相关行是:

git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'; }
HOST='\033[02;36m\]\h'; HOST=' '$HOST
TIME='\033[01;31m\]\t \033[01;32m\]'
LOCATION=' \033[01;34m\]`pwd | sed "s#\(/[^/]\{1,\}/[^/]\{1,\}/[^/]\{1,\}/\).*\(/[^/]\{1,\}/[^/]\{1,\}\)/\{0,1\}#\1_\2#g"`'
BRANCH=' \033[00;33m\]$(git_branch)\[\033[00m\]\n\$ '
PS1=$TIME$USER$HOST$LOCATION$BRANCH
PS2='\[\033[01;36m\]>'
Run Code Online (Sandbox Code Playgroud)

对于可用时带颜色的 ls,不可用时没有错误(即 OSX):

ls --color=al > /dev/null 2>&1 && alias ls='ls -F --color=al' || alias ls='ls -G'
Run Code Online (Sandbox Code Playgroud)

  • @ThomasW 但不在 linux 上 :-p 这家伙同时使用两者。 (3认同)

Ada*_*atz 9

手册页的颜色(更多详细信息):

function _colorman() {
  env \
    LESS_TERMCAP_mb=$(printf "\e[1;35m") \
    LESS_TERMCAP_md=$(printf "\e[1;34m") \
    LESS_TERMCAP_me=$(printf "\e[0m") \
    LESS_TERMCAP_se=$(printf "\e[0m") \
    LESS_TERMCAP_so=$(printf "\e[7;40m") \
    LESS_TERMCAP_ue=$(printf "\e[0m") \
    LESS_TERMCAP_us=$(printf "\e[1;33m") \
      "$@"
}
function man() { _colorman man "$@"; }
function perldoc() { command perldoc -n less "$@" |man -l -; }
Run Code Online (Sandbox Code Playgroud)

grep 的颜色(1;32是亮绿色,其他颜色请参阅此处的其他帖子):

GREP_OPTS='--color=auto'      # for aliases since $GREP_OPTIONS is deprecated
GREP_COLOR='1;32'             # (legacy) bright green rather than default red
GREP_COLORS="ms=$GREP_COLOR"  # (new) Matching text in Selected line = green
alias   grep='grep $GREP_OPTS'
alias egrep='egrep $GREP_OPTS'
alias fgrep='fgrep $GREP_OPTS'
Run Code Online (Sandbox Code Playgroud)

GNU ls 的更多颜色:

# use the config at ~/.dircolors if it exists, otherwise generate anew
eval "$( dircolors --sh $(ls -d ~/.dircolors 2>/dev/null) )"

# Usage: _ls_colors_add BASE NEW [NEW...]
# Have LS color given NEW extensions the way BASE extension is colored
_ls_colors_add() {
  local BASE_COLOR="${LS_COLORS##*:?.$1=}" NEW
  if [ "$LS_COLORS" != "$BASE_COLOR" ]; then
    BASE_COLOR="${BASE_COLOR%%:*}"
    shift
    for NEW in "$@"; do
      if [ "$LS_COLORS" = "${LS_COLORS#*.$NEW=}" ]; then
        LS_COLORS="${LS_COLORS%%:}:*.$NEW=$BASE_COLOR:"
      fi
    done
  fi
  export LS_COLORS
}

_ls_colors_add zip jar xpi            # archives
_ls_colors_add jpg ico JPG PNG webp   # images
_ls_colors_add ogg opus               # audio (opus now included by default)

CLICOLOR=1   # BSD auto-color trigger (like  ls -G  but for everything)
if ls -ld --color=auto / >/dev/null 2>&1
  then alias ls="ls -ph --color=auto"
  else alias ls="ls -ph"
fi
Run Code Online (Sandbox Code Playgroud)

安装grcGeneric Colouriser)并将其添加到您的别名中:

# using this as a variable allows easier calling down lower
export GRC='grc -es --colour=auto'

# loop through known commands plus all those with named conf files
for cmd in g++ head ld ping6 tail traceroute6 `locate grc/conf.`; do
  cmd="${cmd##*grc/conf.}"  # we want just the command
  # if the command exists, alias it to pass through grc
  type "$cmd" >/dev/null 2>&1 && alias "$cmd"="$GRC $cmd"
done

# This needs run-time detection. We even fake the 'command not found' error.
configure() {
  if [[ -x ./configure ]]; then
    colourify ./configure "$@"
  else
    echo "configure: command not found" >&2
    return 127
  fi
}

# GRC plus LS awesomeness (assumes you have an alias for ls)
unalias ll 2>/dev/null
if ls -ld --color=always / >/dev/null 2>&1; then GNU_LS="--color=always"; fi

ll() {
  if [[ -t 1 ]] || [[ -n "$CLICOLOR_FORCE" ]]
    then colourify ls -l $GNU_LS "$@"
    else ls -l "$@"
  fi
}
Run Code Online (Sandbox Code Playgroud)

diff 的颜色:函数的内容过多,请在 rc 文件中使用脚本并将其别名(如果已安装则不需要grc):

#!/usr/bin/perl
use strict;
use warnings;

open (DIFF, "-|", "diff", @ARGV) or die $!;

my $ydiff = 1;
while (<DIFF>) {
  if (not -t 1) {
    print;
    next;
  }
  chomp;
  $ydiff = 0 if /^[ <>\@+-]/ or ($. == 1 && /^\d+[a-z]{1,5}\d+$/);
  my $color = "";
  if (! $ydiff && /^[\@+-<>]/) {
    $color = (/^[<-](?!--$)/ ? 1 : /^[+>]/ ? 2 : 5);
  } elsif ($ydiff && /\t {6}([<|>])(?:\t|$)/) {
    $color = ($1 eq "<" ? 1 : $1 eq ">" ? 2 : 4);
  }
  $color ? printf ("\e[1;3%dm%s\e[0;0m\n",$color,$_) : print "$_\n";
}
close DIFF;
Run Code Online (Sandbox Code Playgroud)

bash 提示的颜色:

# Shorten home dir, cygwin drives, paths that are too long
if [ -d /cygdrive ] && uname -a |grep -qi cygwin; then CYGWIN_OS=1; fi
function PSWD() {
  local p="$*" space A B cols="${COLUMNS:-`tput cols 2>/dev/null || echo 80`}"
  p="${p/$HOME/\~}"         # shrink home down to a tilde
  if [ -n "$CYGWIN_OS" ] && [ "${p#/cygdrive/?/}" != "$p" ]; then
    p="${p:10:1}:${p:11}"   # /cygdrive/c/hi -> c:/hi
  fi
  space="$((${#USER}+${#HOSTNAME}+6))"  # width w/out the path
  if [ "$cols" -lt 60 ]; then echo -n "$N "; space=-29; p="$p$N\b"; fi
  if [ "$cols" -lt "$((space+${#p}+20))" ]; then # < 20 chars for the command
    A=$(( (cols-20-space)/4 ))      # a quarter of the space (-20 for cmd)
    if [ $A -lt 4 ]; then A=4; fi   # 4+ chars from beginning
    B=$(( cols-20-space-A*2 ))      # half (plus rounding) of the space
    if [ $B -lt 8 ]; then B=8; fi   # 8+ chars from end
    p="${p:0:$A}..${p: -$B}"
  fi
  echo "$p"
}

PSC() { echo -ne "\[\033[${1:-0;38}m\]"; }
PR="0;32"       # default color used in prompt is green
if [ "$(id -u)" = 0 ]; then
    sudo=41     # root is red background
  elif [ "$USER" != "${SUDO_USER:-$USER}" ]; then
    sudo=31     # not root, not self: red text
  else sudo="$PR"   # standard user color
fi
PROMPT_COMMAND='[ $? = 0 ] && PS1=${PS1[1]} || PS1=${PS1[2]}'
PSbase="$(PSC $sudo)\u$(PSC $PR)@\h $(PSC 33)\$(PSWD \w)"
PS1[1]="$PSbase$(PSC $PR)\$ $(PSC)"
PS1[2]="$PSbase$(PSC  31)\$ $(PSC)"
PS1="${PS1[1]}"
unset sudo PR PSbase
Run Code Online (Sandbox Code Playgroud)

bash 提示演示


Ste*_*ski 8

设置粗体/彩色提示。来自Cyber​​citi.bizBashFAQ

# 'tput bold' will work regardless of the foreground and background colors.
# Place the tput output into variables, so they are only execd once.
bold=$(tput bold) # This could also be a color.
reset=$(tput sgr0)
export PS1="\u@\[$bold\]\h\[$reset\]:\w \$ "
Run Code Online (Sandbox Code Playgroud)

我还设法找到了广泛支持的颜色设置,并且在旧环境(甚至 FreeBSD4!)中不打印 gobbledygook 字符,并且如果 TERM=vt100、xterm、xterm-color 似乎工作正常。(在大多数情况下)。从我的 .bashrc:

# Set some options, based on the OS
OS=`uname -s` 

case "$OS" in
    "SunOS" ) 
        # Solaris ls doesn't allow color, so use special characters
        LS_OPTS='-F'
        alias  ls='ls ${LS_OPTS}'
        ;;
    "Linux" )
        # GNU ls supports colors!
        # See dircolors to customize colors
        export LS_OPTS='--color=auto' 
        alias  ls='ls ${LS_OPTS}'

        # Get color support for 'less'
        export LESS="--RAW-CONTROL-CHARS"

        # Use colors for less, man, etc.
        [[ -f ~/.LESS_TERMCAP ]] && . ~/.LESS_TERMCAP

        export GREP_OPTIONS="--color=auto"

        ;;
    "Darwin"|"FreeBSD")

        # Most FreeBSD & Apple Darwin supports colors
        export CLICOLOR=true
        # Get color support for 'less'
        export LESS="--RAW-CONTROL-CHARS"

        # Use colors for less, man, etc.
        [[ -f ~/.LESS_TERMCAP ]] && . ~/.LESS_TERMCAP

        export GREP_OPTIONS="--color=auto"
        ;;
    * ) 
        echo "Unknown OS [$OS]"
        ;;
esac
Run Code Online (Sandbox Code Playgroud)


小智 7

这里没有说的事情:

要使用 gcc 对编译的输出进行着色,请使用 Johannes Schlüter 的 colorgcc

为了给原木着色,有 multitail

为了给任何标准输出着色,我把xcol放在一起

xcol 示例

我个人使用 xcol 工具中的这些。

#normal=$(tput sgr0)                      # normal text
normal=$'\e[0m'                           # (works better sometimes)
bold=$(tput bold)                         # make colors bold/bright
red="$bold$(tput setaf 1)"                # bright red text
green=$(tput setaf 2)                     # dim green text
fawn=$(tput setaf 3); beige="$fawn"       # dark yellow text
yellow="$bold$fawn"                       # bright yellow text
darkblue=$(tput setaf 4)                  # dim blue text
blue="$bold$darkblue"                     # bright blue text
purple=$(tput setaf 5); magenta="$purple" # magenta text
pink="$bold$purple"                       # bright magenta text
darkcyan=$(tput setaf 6)                  # dim cyan text
cyan="$bold$darkcyan"                     # bright cyan text
gray=$(tput setaf 7)                      # dim white text
darkgray="$bold"$(tput setaf 0)           # bold black = dark gray text
white="$bold$gray"                        # bright white text
Run Code Online (Sandbox Code Playgroud)

我像这样在我的脚本中使用这些变量

echo "${red}hello ${yellow}this is ${green}coloured${normal}"
Run Code Online (Sandbox Code Playgroud)

我也喜欢这个小函数 colouredEcho(在 Stack Overflow 上找到)

function coloredEcho(){
    local exp=$1;
    local color=$2;
    if ! [[ $color =~ '^[0-9]$' ]] ; then
       case $(echo $color | tr '[:upper:]' '[:lower:]') in
        black) color=0 ;;
        red) color=1 ;;
        green) color=2 ;;
        yellow) color=3 ;;
        blue) color=4 ;;
        magenta) color=5 ;;
        cyan) color=6 ;;
        white|*) color=7 ;; # white or invalid color
       esac
    fi
    tput setaf $color;
    echo $exp;
    tput sgr0;
}

coloredEcho "This text is green" green
Run Code Online (Sandbox Code Playgroud)

对不起,不允许发布更多链接

  • 你好,你如何制作标志,提示路径?我说的是三角形末端的矩形条谢谢 (2认同)

小智 5

有一个很好的工具可以为 ls 命令设置颜色 - http://geoff.greer.fm/lscolors/


小智 5

我建议您查看ZSH及其插件oh-my-zsh,它具有我见过的最强大的控制台功能之一。其中之一是为您的终端选择主题。这是我的主题的示例...在 tty 中,颜色不是那么温暖,但它们与这张图片中的相同...无论如何你都会喜欢它!

在此输入图像描述

  • 如果可以的话,我会否决 Oh-My-ZSH 建议。作为一名在终端中广泛工作的系统工程师,以及作为尝试将 zsh/oh-my-zsh 采用到我的工作流程中的人,我可以诚实地说我永远不会向任何人推荐 ZSH。当然,您可以将 zsh 符号链接到以任何其他 shell 命名的文件并模拟该 shell,但是当您这样做时,它不会读取您的 .bashrc、.bash_profile 等。此外,您不能将“模拟 bash”放入您的 .bashrc 文件中。 zprofile 或 .zshrc 文件。对于任何使用 BASH 高级功能的人来说,有许多微妙之处会让您感到困惑。BASH 是一个更好的 sh。 (3认同)
  • ZSH 开箱即用的唯一比 BASH 更好的就是命令完成,但即便如此,它也可以在 BASH 中进行编程。也许除了偶尔执行日常任务之外不使用 shell 的人应该采用 ZSH,但这并不适合需要广泛使用 shell 的人。`=~` 操作符可能会影响你,ZSH 处理数组的方式也会影响你,等等。在使用 ZSH/Oh-My-ZSH 大约 9 个月后,我已经受够了。我使用的是我自己编写的自定义主题,我将其移植到 BASH 并编写了我自己的 git 提示行,并且我从未回头。现在我不再担心便携性 (3认同)
  • “它具有我见过的最强大的控制台功能之一。其中之一就是为您的终端选择主题。” (2认同)
  • 感谢您的关心,但我的评论说出了我想说的一切。 (2认同)