How can I display the current branch and folder path in terminal? Ask Question

How can I display the current branch and folder path in terminal? Ask Question

I've been watching some of the Team Treehouse videos and they have a very nice looking terminal when working with Git.

For example they have (something similar):

mike@treehouseMac: [/Work/test - feature-branch-name] $ git add .
mike@treehouseMac: [/Work/test - feature-branch-name] $ git commit -m "Some feature."
mike@treehouseMac: [/Work/test - feature-branch-name] $ git checkout master
mike@treehouseMac: [/Work/test - master] $ git status

How can my terminal show me some useful information of what branch I'm on, with colors to distinguish bits of the data I want? Is there some sort of de-facto plugin I haven't found yet?

I'm using Mac OSX 10.8

ベストアンサー1

For anyone looking for how to do this in macOS Catalina or above (10.15+ incl. Big Sur 11.0) which has deprecated bash in favour of zsh, here is my .zshrc file:

parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF='%f'
COLOR_USR='%F{243}'
COLOR_DIR='%F{197}'
COLOR_GIT='%F{39}'
# About the prefixed `$`: https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_03.html#:~:text=Words%20in%20the%20form%20%22%24',by%20the%20ANSI%2DC%20standard.
NEWLINE=$'\n'
# Set zsh option for prompt substitution
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n@%M ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}${NEWLINE}%% '

私が使用した色が気に入らない場合は、243/197/39 の値を、ここで定義されているカラー コードに置き換えてください。https://misc.flogisoft.com/bash/tip_colors_and_formatting

迅速な代替使用済み:

  • %n: ユーザー名
  • %M: 完全なマシンホスト名
  • %d: 現在の作業ディレクトリ
  • %%: 印刷するためのエスケープシーケンス%

おすすめ記事