터미널과 셸 환경에 색상을 지정하시겠습니까?

터미널과 셸 환경에 색상을 지정하시겠습니까?

저는 대부분의 시간을 Unix 환경에서 작업하고 터미널 에뮬레이터를 사용하는 데 보냅니다. 저는 명령줄에서 색상을 사용하려고 합니다. 왜냐하면 색상이 출력을 더욱 유용하고 직관적으로 만들어주기 때문입니다.

터미널 환경에 색상을 추가할 수 있는 옵션은 무엇입니까? 어떤 트릭을 사용합니까? 어떤 함정에 직면했나요?

안타깝게도 색상 지원은 터미널 유형, OS, TERM 설정, 유틸리티, 버그 구현 등에 따라 다릅니다.

다음은 많은 실험을 거친 후 설정에서 얻은 몇 가지 팁입니다.

  1. TERM=xterm-color나는 대부분의 호스트에서 지원되는(전부는 아니지만) 설정하는 경향이 있습니다 .
  2. 저는 다양한 호스트, 다양한 OS 버전 등에서 작업합니다. macOS X, Ubuntu Linux, RHEL/CentOS/Scientific Linux 및 FreeBSD의 모든 것을 사용합니다. 가능하다면 간단하고 일반적인 내용을 유지하려고 노력하고 있습니다.
  3. screen나는 또 다른 재미를 더해주는 GNU를 사용하여 많은 작업을 수행합니다 .
  4. 많은 OS는 dircolors기본적으로 와 같은 것을 설정하고 있으며 수백 개의 다른 호스트에서 이것을 수정하고 싶지 않습니다. 그래서 저는 기본값을 고수하려고 노력합니다. 대신 터미널의 색상 구성을 조정했습니다.
  5. 일부에는 색상을 사용하십시오.유닉스 명령( ls, grep, less, vim) 그리고배쉬 프롬프트. 이 명령은 표준 "ANSI 이스케이프 시퀀스". 예를 들어:

    alias less='less --RAW-CONTROL-CHARS'
    export LS_OPTS='--color=auto'
    alias ls='ls ${LS_OPTS}'
    

나는 내 .bashrc질문을 게시하고 Jeopardy Style에 답변하겠습니다.

답변1

다음과 같은 몇 가지 작업을 수행할 수 있습니다.

편집자 + 코드
많은 편집기에는 구문 강조 기능이 지원됩니다. 기본적으로 켜져 있습니다 vim. emacs당신은 또한 수아래에서 활성화하세요nano.

다음을 사용하여 터미널에서 구문 강조 코드를 사용할 수도 있습니다.피그먼트명령줄 도구로 사용됩니다.

grep
grep --color=auto모든 경기를 강조 표시합니다. export GREP_OPTIONS='--color=auto'별칭 없이 이를 지속성으로 만드는 데 사용할 수도 있습니다 . 을 사용하면 --color=always,배관시에도 색상을 사용, 상황을 혼란스럽게 만듭니다.

ㅋㅋㅋ

ls --color=always

색상 지정:

export LS_COLORS='rs=0:di=01;34:ln=01;36:mh=00:pi=40;33'

(힌트: dircolors도움이 될 수 있습니다)

PS1
색상을 사용하도록 PS1(쉘 프롬프트)을 설정할 수 있습니다. 예를 들어:

PS1='\e[33;1m\u@\h: \e[31m\W\e[0m\$ '

다음과 같은 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]\$ '

임의의 정보가 포함된 막대를 터미널 상단에 표시합니다. (최상의 결과를 얻으려면 를 사용하세요 alias clear="echo -e '\e[2J\n\n'".)

이스케이프 시퀀스 제거하기

원하지 않는 색상 출력이 중단된 경우 다음 sed줄을 사용하여 이스케이프 시퀀스를 제거합니다.

sed "s/\[^[[0-9;]*[a-zA-Z]//gi"

보다 실제적인 경험을 원한다면 \e[8m터미널에 텍스트를 숨기도록 지시하는 로 시작하는 줄을 제거할 수도 있습니다. (널리 지원되지는 않습니다.)

sed "s/^\[^[8m.*$//gi"

또한 해당 ^[s는 실제 리터럴 ^[s여야 합니다. bash에서 ^V^[ 즉, Ctrl+ V, Ctrl+ 를 눌러 입력할 수 있습니다 [.

답변2

나는 또한 다음을 사용합니다:

export TERM=xterm-color
export GREP_OPTIONS='--color=auto' GREP_COLOR='1;32'
export CLICOLOR=1
export LSCOLORS=ExFxCxDxBxegedabagacad

프롬프트에 색상을 지정하고 싶다면 정의된 색상 변수가 유용할 수 있습니다.

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'

그리고 내 메시지는 다음과 같습니다.

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}\] "  

$(vcprompt)는 현재 경로에 대한 버전 제어 정보를 인쇄하는 ~/sbin에서 Python 스크립트를 호출하고 있습니다. 여기에는 Mercurial, Git, Svn, Cvs 등에 대한 지원이 포함됩니다. 스크립트 작성자는출처는 여기.

Bash 프롬프트 스크린샷

이것이전체 소스내 프롬프트 구성 중:

답변3

grep이미 언급한 바 있으니 ls더 많은 색상을 원하시면 확인해 보세요.일반 컬러라이저, 초기 목적은 로그 파일을 색상화하는 것이었지만 즉시 ping, traceroute, gcc, make, netstat, , 및 에도 색상 diff을 지정합니다 .lastldapcvs

정규 표현식을 알고 있으면 쉽게 확장할 수 있습니다. 목록에 ps및를 추가했습니다. (만약 목록에 참여하시면 해당 두 도구에 대한 .conf 파일을 기꺼이 공유하겠습니다.)nmapgrc

synaptic(그런데 , 등을 통해 설치하려면 pacman"grc"를 검색하는 것이 더 나을 수도 있습니다)

답변4

색상매뉴얼 페이지(자세한 세부 사항):

function _colorman() {
  env \
    LESS_TERMCAP_mb=$'\e[1;35m' \
    LESS_TERMCAP_md=$'\e[1;34m' \
    LESS_TERMCAP_me=$'\e[0m' \
    LESS_TERMCAP_se=$'\e[0m' \
    LESS_TERMCAP_so=$'\e[7;40m' \
    LESS_TERMCAP_ue=$'\e[0m' \
    LESS_TERMCAP_us=$'\e[1;33m' \
    LESS_TERMCAP_mr=$(tput rev) \
    LESS_TERMCAP_mh=$(tput dim) \
    LESS_TERMCAP_ZN=$(tput ssubm) \
    LESS_TERMCAP_ZV=$(tput rsubm) \
    LESS_TERMCAP_ZO=$(tput ssupm) \
    LESS_TERMCAP_ZW=$(tput rsupm) \
    GROFF_NO_SGR=1 \
      "$@"
}
alias man="LANG=C _colorman man"
function perldoc() { command perldoc -n less "$@" |man -l -; }

색상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
# (new) Matching text in Selected line = green, line numbers dark yellow
GREP_COLORS="ms=${GREP_COLOR}:mc=${GREP_COLOR}:ln=33"
alias grep='grep $GREP_OPTS'
alias egrep='grep -E $GREP_OPTS'
alias fgrep='LC_ALL=C grep -F $GREP_OPTS'

LC_ALL=Cfgrep을 사용하면 다음을 제공할 수 있습니다.140배 성능 향상

더 많은 색상GNU ls:

# use the config at ~/.dircolors if it exists, otherwise generate anew
eval "$( dircolors --sh $(find ~/.dircolors -size +0 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)

export 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

설치하다grc(일반 컬러라이저) 별칭에 추가합니다.

if type grc grcat >/dev/null 2>&1; then
  colourify() {  # using this as a function allows easier calling down lower
    if [[ -t 1 || -n "$CLICOLOR_FORCE" ]]
      then ${GRC:-grc} -es --colour=auto "$@"
      else "$@"
    fi
  }

  # 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
    type "$cmd" >/dev/null 2>&1 && alias "$cmd"="colourify $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
  }

  unalias ll 2>/dev/null
  ll() {
    if [[ -n "$CLICOLOR_FORCE" || -t 1 ]]; then  # re-implement --color=auto
      ls -l --color=always "$@" |grcat conf.ls
      return ${PIPESTATUS[0]} ${pipestatus[1]} # exit code of ls via bash or zsh
    fi
    ls -l "$@"
  }
fi

색상차이점: 함수에 대한 내용이 너무 많습니다. 스크립트를 사용하고 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;

색상배쉬 프롬프트:

# Shorten home dir, Cygwin drives, paths that are too long
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 [ -d /cygdrive ] && [ "${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() { printf $'\[\e[%sm\]' "${*:-0;0}"; }
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

Bash 프롬프트 데모

관련 정보