git 如何在终端中显示当前分支和文件夹路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17333531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I display the current branch and folder path in terminal?
提问by sergserg
I've been watching some of the Team Treehouse videos and they have a very nice looking terminal when working with Git.
我一直在观看 Team Treehouse 的一些视频,他们在使用 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
我使用的是 Mac OSX 10.8
采纳答案by janos
It's not about a plugin. It's about prompt tricks in the shell.
这与插件无关。这是关于 shell 中的提示技巧。
For a cool setup in bash, check out the dotfiles
project of this guy:
要在 bash 中进行很酷的设置,请查看dotfiles
此人的项目:
https://github.com/mathiasbynens/dotfiles
https://github.com/mathiasbynens/dotfiles
To get a fancy prompt, include the .bash_prompt
in your ~/.bash_profile
or ~/.bashrc
.
要获得花哨的提示,.bash_prompt
请将包含在您的~/.bash_profile
或 中~/.bashrc
。
To get the exact same prompt as in your question, change the export PS1
line at the end of .bash_prompt
like this:
要获得与您的问题完全相同的提示,请像这样更改export PS1
末尾的行.bash_prompt
:
export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]$([[ -n $(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]$(parse_git_branch)\[$WHITE\]] $ \[$RESET\]"
I ended up using all the .bash*
files from this repository about a month ago, and it's been really useful for me.
.bash*
大约一个月前,我最终使用了这个存储库中的所有文件,这对我来说非常有用。
For Git, there are extra goodies in .gitconfig
.
对于 Git,.gitconfig
.
And since you're a mac user, there are even more goodies in .osx
.
而且由于您是 mac 用户,因此.osx
.
回答by 6LYTH3
Simple way
简单的方法
Open ~/.bash_profile
in your favorite editor and add the following content to the bottom.
~/.bash_profile
在你最喜欢的编辑器中打开并在底部添加以下内容。
Git branch in prompt.
提示中的 Git 分支。
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ ()/'
}
export PS1="\u@\h \[3[32m\]\w - $(parse_git_branch)\[3[00m\] $ "
回答by sergserg
To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfilesproject.
为了扩展现有的优秀答案,获得漂亮终端的一种非常简单的方法是使用开源Dotfiles项目。
https://github.com/mathiasbynens/dotfiles
https://github.com/mathiasbynens/dotfiles
Installation is dead simple on OSX and Linux. Run the following command in Terminal.
在 OSX 和 Linux 上安装非常简单。在终端中运行以下命令。
git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh
This is going to:
这将:
- Git clone the repo.
cd
into the folder.- Run the installation bash script.
- Git 克隆存储库。
cd
到文件夹中。- 运行安装 bash 脚本。
回答by romiem
For anyone looking for how to do this in macOS Catalina (10.15) which is deprecating bash in favour of zsh, here is my .zshrc file:
对于那些在 macOS Catalina (10.15) 中寻找如何做到这一点的人来说,它正在弃用 bash 而支持 zsh,这是我的 .zshrc 文件:
parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[]/p'
}
COLOR_DEF=$'\e[0m'
COLOR_USR=$'\e[38;5;243m'
COLOR_DIR=$'\e[38;5;197m'
COLOR_GIT=$'\e[38;5;39m'
NEWLINE=$'\n'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n@%M ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}${NEWLINE}%% '
If you don't like the colours I have used, replace the 243/197/39 values with the colour codes as defined here: https://misc.flogisoft.com/bash/tip_colors_and_formatting
如果您不喜欢我使用的颜色,请将 243/197/39 值替换为此处定义的颜色代码:https://misc.flogisoft.com/bash/tip_colors_and_formatting
回答by Tom Hale
My prompt includes:
我的提示包括:
- Exit status of last command (if not 0)
- Distinctive changes when root
rsync
-styleuser@host:pathname
for copy-paste goodness- Git branch, index, modified, untracked and upstream information
- Pretty colours
- 最后一条命令的退出状态(如果不是 0)
- root时的显着变化
rsync
-user@host:pathname
复制粘贴善良的风格- Git 分支、索引、修改、未跟踪和上游信息
- 漂亮的颜色
Example:
To do this, add the following to your
~/.bashrc
:
#
# Set the prompt #
#
# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1 # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1 # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1 # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose" # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR='' # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe" # detached HEAD style:
# contains relative to newer annotated tag (v1.6.3.2~35)
# branch relative to newer tag or branch (master~4)
# describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
# default exactly eatching tag
# Check if we support colours
__colour_enabled() {
local -i colors=$(tput colors 2>/dev/null)
[[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1
__set_bash_prompt()
{
local exit="$?" # Save the exit status of the last command
# PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
local PreGitPS1="${debian_chroot:+($debian_chroot)}"
local PostGitPS1=""
if [[ $__colourise_prompt ]]; then
export GIT_PS1_SHOWCOLORHINTS=1
# Wrap the colour codes between \[ and \], so that
# bash counts the correct number of characters for line wrapping:
local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
local None='\[\e[0m\]' # Return to default colour
# No username and bright colour if root
if [[ ${EUID} == 0 ]]; then
PreGitPS1+="$BRed\h "
else
PreGitPS1+="$Red\u@\h$None:"
fi
PreGitPS1+="$Blu\w$None"
else # No colour
# Sets prompt like: ravi@boxy:~/prj/sample_app
unset GIT_PS1_SHOWCOLORHINTS
PreGitPS1="${debian_chroot:+($debian_chroot)}\u@\h:\w"
fi
# Now build the part after git's status
# Highlight non-standard exit codes
if [[ $exit != 0 ]]; then
PostGitPS1="$Red[$exit]"
fi
# Change colour of prompt if root
if [[ ${EUID} == 0 ]]; then
PostGitPS1+="$BRed"'$ '"$None"
else
PostGitPS1+="$Mag"'$ '"$None"
fi
# Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
__git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'
# echo '$PS1='"$PS1" # debug
# defaut Linux Mint 17.2 user prompt:
# PS1='${debian_chroot:+($debian_chroot)}\[3[01;32m\]\u@\h\[3[01;34m\] \w\[3[00m\] $(__git_ps1 "(%s)") $ '
}
# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt
回答by amy2719
Just Install the oh-my-zsh
plugins as described in this link.
只需oh-my-zsh
按照此链接中的说明安装插件。
It works best on macOS and Linux.
它在 macOS 和 Linux 上效果最好。
Basic Installation
基本安装
Oh My Zsh is installed by running one of the following commands in your terminal. You can install this via the command-line with either curl
or wget
.
Oh My Zsh 是通过在终端中运行以下命令之一来安装的。您可以通过命令行使用curl
或安装它wget
。
via curl
通过卷曲
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
via wget
通过 wget
sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
回答by Chadversary
The git package installed on your system includes bash files to aid you in creating an informative prompt. To create colors, you will need to insert terminal escape sequences into your prompt. And, the final ingredient is to update your prompt after each command gets executed by using the built-in variable PROMPT_COMMAND.
安装在您系统上的 git 包包含 bash 文件,以帮助您创建信息提示。要创建颜色,您需要在提示中插入终端转义序列。并且,最后一个要素是在使用内置变量 PROMPT_COMMAND 执行每个命令后更新您的提示。
Edit your ~/.bashrc to include the following, and you should get the prompt in your question, modulo some color differences.
编辑您的 ~/.bashrc 以包含以下内容,您应该在问题中得到提示,以一些颜色差异为模。
#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh
#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'
#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"${color_start}${color_bg_blue}${color_end}\u@\h [\w$(__git_ps1 \" - %s\")]${color_reset}\n$ \""
#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3
回答by Anver Sadhat
回答by Jose Paez
Based on 6LYTH3's answer I've decided to post my own due to some improvements that may come in handy:
基于 6LYTH3 的回答,我决定发布自己的回答,因为一些改进可能会派上用场:
Simple solution
简单的解决方案
Open ~/.bash_profile
and add the following content
打开~/.bash_profile
并添加以下内容
# \[\e[0m\] resets the color to default color
reset_color='\[\e[0m\]'
# \[3[33m\] sets the color to yellow
path_color='\[3[33m\]'
# \e[0;32m\ sets the color to green
git_clean_color='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
git_dirty_color='\[\e[0;31m\]'
# determines if the git branch you are on is clean or dirty
git_prompt ()
{
# Is this a git directory?
if ! git rev-parse --git-dir > /dev/null 2>&1; then
return 0
fi
# Grab working branch name
git_branch=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
git_color="${git_clean_color}"
else
git_color="${git_dirty_color}"
fi
echo " [$git_color$git_branch${reset_color}]"
}
export PS1="${path_color}\w\[\e[0m\]$(git_prompt)\n"
This should:
这应该:
1) Prompt the path you're in, in color: path_color.
2) Tell you which branch are you.
3) Color the name of the branch based on the status of the branch with git_clean_color
for a clean work directory and git_dirty_color for a dirty one.
4) The brackets should stay in the default color you established in your computer.
5) Puts the prompt in the next line for readability.
You can customize the colors with this list
您可以使用此列表自定义颜色
Sophisticated Solution
成熟的解决方案
Another option is to use Git Bash Prompt, install with this. I used the option via Homebrew on Mac OS X.
另一种选择是使用 Git Bash Prompt,使用此. 我在 Mac OS X 上通过 Homebrew 使用了该选项。
git_prompt_list_themes
to see the themes but I didn't like any of them.
git_prompt_list_themes
看主题,但我不喜欢其中任何一个。
git_prompt_color_samples
to see available colors.
git_prompt_color_samples
查看可用的颜色。
git_prompt_make_custom_theme [<Name of base theme>]
to create a new custom theme, this should create a .git-prompt-colors.sh file.
git_prompt_make_custom_theme [<Name of base theme>]
要创建一个新的自定义主题,这应该创建一个 .git-prompt-colors.sh 文件。
subl ~/.git-prompt-colors.sh
to open git-prompt-colors.sh and customize:
subl ~/.git-prompt-colors.sh
打开 git-prompt-colors.sh 并自定义:
The .git-prompt-colors.sh file should look like this with my customization
.git-prompt-colors.sh 文件应该与我的自定义类似
override_git_prompt_colors() {
GIT_PROMPT_THEME_NAME="Custom"
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
GIT_PROMPT_BRANCH="${Green}"
else
GIT_PROMPT_BRANCH="${Red}"
fi
}
reload_git_prompt_colors "Custom"
Hope this helps, have a great day!
希望这会有所帮助,祝您有美好的一天!
回答by ssppjj
In 2019, I think git branch --show-current
is a better command than the accepted answer.
在 2019 年,我认为这git branch --show-current
是一个比公认的答案更好的命令。
$ git branch --show-current
master
(Added in git 2.22 release in June 2019)
(在 2019 年 6 月的 git 2.22 版本中添加)
It runs much faster as it doesn't need to iterate through all branches. Similarly git branch
should be avoided too in the command prompt as it slows down your prompt if you have many local branches.
它运行得更快,因为它不需要遍历所有分支。同样git branch
,在命令提示符中也应该避免,因为如果您有许多本地分支,它会减慢您的提示速度。
Put it in a function to use anywhere on command prompt:
把它放在一个函数中以在命令提示符的任何地方使用:
# This function returns '' in all below cases:
# - git not installed or command not found
# - not in a git repo
# - in a git repo but not on a branch (HEAD detached)
get_git_current_branch() {
git branch --show-current 2> /dev/null
}
More context:
更多背景:
$ git version
git version 2.23.0