2014-07-19 2 views
2

다음 스크립트를 사용하여 bash 프롬프트를 다음과 같이 설정하려고합니다. 모든 것이 작동하지만 Git 저장소의 브랜치 이름과 브랜치의 상태를 컬러로 인쇄하는 부분입니다. 색상은 다소 임의적이지만, 파일이 커밋되지 않은 경우 빨간색, 파일이 스테이지되지 않은 경우 노란색, 다른 것이 녹색 인 경우에는 말할 필요도 없습니다. 흰 생각에 내가 원하는 부분을 인쇄하고있어. 내가 마지막 부분으로 $branchStyle을 개별적으로 정의하는 스크립트의 일부를 실행하면 작동하지만 여기에는 포함되지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?bash 프롬프트에서 git 상태의 색상 설정

prompt_git() { 
    local s="" 
    local branchName="" 

    # check if the current directory is in a git repository 
    if [ $(git rev-parse --is-inside-work-tree &>/dev/null; printf "%s" $?) == 0 ]; then 

     # check if the current directory is in .git before running git checks 
     if [ "$(git rev-parse --is-inside-git-dir 2> /dev/null)" == "false" ]; then 

      # ensure index is up to date 
      git update-index --really-refresh -q &>/dev/null 

      # check for uncommitted changes in the index 
      if ! $(git diff --quiet --ignore-submodules --cached); then 
       s="$s+"; 
      fi 

      # check for unstaged changes 
      if ! $(git diff-files --quiet --ignore-submodules --); then 
       s="$s!"; 
      fi 

      # check for untracked files 
      if [ -n "$(git ls-files --others --exclude-standard)" ]; then 
       s="$s?"; 
      fi 

      # check for stashed files 
      if $(git rev-parse --verify refs/stash &>/dev/null); then 
       s="$s$"; 
      fi 

     fi 

     # get the short symbolic ref 
     # if HEAD isn't a symbolic ref, get the short SHA 
     # otherwise, just give up 
     branchName="$(git symbolic-ref --quiet --short HEAD 2> /dev/null || \ 
        git rev-parse --short HEAD 2> /dev/null || \ 
        printf "(unknown)")" 

     [ -n "$s" ] && s=" [$s]" 

     printf "%s" "$1$branchName$s" 
    else 
     return 
    fi 
} 

set_prompts() { 

    local bold=$(tput bold) 
    local reset=$(tput sgr0) 
    local base05=$(tput setaf 188) # light grey 
    local base08=$(tput setaf 210) # red 
    local base0A=$(tput setaf 221) # yellow 
    local base0B=$(tput setaf 114) # green 

    if git rev-parse --git-dir >/dev/null 2>&1; then 
     # check for uncommitted changes in the index 
     if ! git diff-index --quiet --cached HEAD --ignore-submodules -- >&2; then 
      branchStyle=$base08 
     # check for unstaged changes 
     elif ! git diff-files --quiet --ignore-submodules -- >&2; then 
      branchStyle=$base0A 
     else 
      branchStyle=$base0B 
     fi 
    fi 

    PS1+="\$(prompt_git \"$bold$base05 on $branchStyle\")" # git repository details 

    export PS1 
} 

set_prompts 
unset set_prompts 
+0

문제를 나타내는 짧은 테스트 사례가 있습니까? [bash 태그 위키] (http : // stackoverflow.co.kr/tags/bash/info)에는 게시 된 코드 크기를 줄이는 방법에 대한 팁이 있습니다. –

+0

@thatotherguy, k, 나는 스크립트에 필요한 것 같지 않은 모든 것을 꺼 냈습니다. 본질적으로'prompt_git' 함수는 repo에서 변경된 것을 찾고 문자열을 추가하여 프롬프트에서 볼 수 있도록 설계되었습니다. 그리고 커밋되지 않은 변경이나 unstaged 변경이 있는지를 결정하는'set_prompts' 함수에서 다른 검사를합니다 그에 따라 색상을 설정합니다. 나는이 모든 것이 1 또는 많은 함수에서 행해졌으므로, 최선의 결과는 무엇이든 상관 없다. – chrisopedia

+0

스크립트에 필요없는 내용 만 제거하지 마십시오. 게시하려는 특정 색상 문제를 재현하지 않아도되는 내용은 모두 제거하십시오. 예를 들어 문제를 재연하는 데 충분합니까? 'echo $ (tput setaf 210) 왜이 텍스트는 핑크색이 아닌 흰색 " –

답변

0

가 모든 단말기는 3 개 자리 숫자를 지원하기 위해 보이지만, 일부는 사람의 terminfo에 선언 된 휴대용 8 색으로 제한됩니다 : 그래서

Color  #define  Value  RGB 
black  COLOR_BLACK  0  0, 0, 0 
red  COLOR_RED   1  max,0,0 
green  COLOR_GREEN  2  0,max,0 
yellow COLOR_YELLOW  3  max,max,0 
blue  COLOR_BLUE  4  0,0,max 
magenta COLOR_MAGENTA  5  max,0,max 
cyan  COLOR_CYAN  6  0,max,max 
white  COLOR_WHITE  7  max,max,max 

, 내가 생각하는 문제는의 사용이다 높은 색상 번호.

(x=`tput op` y=`printf %$((${COLUMNS}-6))s`;for i in {0..256};do o=00$i;echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x;done;) 

당신이보고있는 문제를 재현하는 데 필요한 코드의 최소한의 조각을 줄이기 위해 어떤 문제에 대한 좋은 방법 http://www.commandlinefu.com/commands/view/6533/print-all-256-colors-for-testing-term-or-for-a-quick-reference

+0

Mine은 256을 지원하므로 스크립트를 넣으면 256 가지 색상이 출력됩니다. – chrisopedia

2

에서 : 당신은 출력이 같은 터미널에 대한 색상 표 수 있습니다. 이렇게하면 디버깅이 쉬워지고 다른 사람들이 쉽게 읽고 해결할 수 있으며 다른 사용자가 혜택을 볼 수 있다는 일반적인 질문을하게됩니다. 당신이 당신의 문제로 보면

예를 들어, 당신은 그것을 볼 수 있습니다 :

  • 그것은 prompt_git 기능과 관련이없는 것 : 간단한 에코로 교체 할 때 같은 일이 발생합니다.
  • 색상과 관련이 없습니다. 일반 문자열을 사용하면 똑같은 일이 발생합니다.
  • unstaged 또는 uncommited 파일과 관련이 없습니다. 이러한 검사를 건너 뛰면 동일한 문제가 발생합니다.
  • git과 전혀 관련이 없습니다. 단지 디렉토리를 비교하면 똑같은 일이 발생합니다.

이제 우리는 잘못을 정확하게 표시하는 작은 코드 샘플 질문을 작성할 수 있습니다

은 내가에게 cd /tmp "/ tmp 디렉토리에"표시하는 다음 코드 조각을 예상, 대신 프롬프트가 공백으로 남습니다. 왜 업데이트되지 않습니까?
set_prompts() { 
    message="" 
    if [[ $PWD/ == /tmp/* ]] 
    then 
    message="in /tmp" 
    fi 
    PS1="\$(echo $message) \$" 
} 
set_prompts 
unset set_prompts 

이 질문에

읽고 대답하기 매우 쉽습니다 : set_prompts 실행을 한 번 $message에 대한 값을 계산 한 다음 그것을 해제하고 다시는 실행되지이다. 이것이 메시지가 결코 바뀌지 않는 이유입니다.

작동 시키려면 모든 프롬프트를 재생성하기 전에 다시 실행해야합니다. 이것은 PROMPT_COMMAND으로 수행 할 수 있습니다

이 예상, 쉽게 코드의 실제, 긴 조각에 적용 할 수 있습니다로 작동
set_prompts() { 
    PS1='\[email protected]\h:\w '     # <-- Reset PS1 before each run 
    message="" 
    if [[ $PWD/ == /tmp/* ]] 
    then 
    message="in /tmp" 
    fi 
    PS1="\$(echo $message) \$" 
}  
PROMPT_COMMAND='set_prompts'  # <-- Run function before every prompt 

.

관련 문제