Loading
2017. 11. 23. 22:57 - leee.sangwon

GIT branch 이름과 상태를 bash shell에 표시하기

아래 글을 따라 ~/.bashrc에 추가해주면 된다.

원글: https://coderwall.com/p/pn8f0g/show-your-git-status-and-branch-in-color-at-the-command-prompt


I'm a huge fan of having the branch and status for my current project reflected in my bash prompt. Here's what mine looks like:


And here's how to get that:

First define some colors. This will make it easier to work with the escape sequences later:

먼저 사용할 몇가지 색상을 정의한다:

COLOR_RED="\033[0;31m"
COLOR_YELLOW="\033[0;33m"
COLOR_GREEN="\033[0;32m"
COLOR_OCHRE="\033[38;5;95m"
COLOR_BLUE="\033[0;34m"
COLOR_WHITE="\033[0;37m"
COLOR_RESET="\033[0m"

Next, a function for the color formatting:

현재 git 상태에 맞게 색상을 설정해주는 함수를 작성한다:

function git_color {
  local git_status="$(git status 2> /dev/null)"

  if [[ ! $git_status =~ "working directory clean" ]]; then
    echo -e $COLOR_RED
  elif [[ $git_status =~ "Your branch is ahead of" ]]; then
    echo -e $COLOR_YELLOW
  elif [[ $git_status =~ "nothing to commit" ]]; then
    echo -e $COLOR_GREEN
  else
    echo -e $COLOR_OCHRE
  fi
}

and one for the git branch:

현재 git branch 또는 commit id을 불러오는 함수를 작성한다:

function git_branch {
  local git_status="$(git status 2> /dev/null)"
  local on_branch="On branch ([^${IFS}]*)"
  local on_commit="HEAD detached at ([^${IFS}]*)"

  if [[ $git_status =~ $on_branch ]]; then
    local branch=${BASH_REMATCH[1]}
    echo "($branch)"
  elif [[ $git_status =~ $on_commit ]]; then
    local commit=${BASH_REMATCH[1]}
    echo "($commit)"
  fi
}

NB: The formatting of git status messages has changed, so if you're on the latest version of git, you'll likely need to use"^On branch instead of "^# On branch above. Check your git status to be sure you're using the right string.

Lastly, incorporate into the PS1 declaration (broken up for clarity):

마지막으로 PS1을 선언해준다.

PS1="\[$COLOR_WHITE\]\n[\W]"          # basename of pwd 원래 사용하던 설정이 있다면 여기에 넣으면 된다.
PS1+="\[\$(git_color)\]"        # colors git status
PS1+="\$(git_branch)"           # prints current branch
PS1+="\[$COLOR_BLUE\]\$\[$COLOR_RESET\] "   # '#' for root, else '$'
export PS1

Voila!