Show current Git branch and status in your prompt

本文介绍如何在 Bash 中配置 Git 的自动补全功能,并展示如何修改提示符以显示当前 Git 仓库的状态,包括分支名称及是否有未提交的更改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://www.bramschoenmakers.nl/en/node/624


Those who use git frequently will often execute commands like git status and git branch to check which branch you're on and if there are pending changes.

Fortunately, git offers a Bash script which automatically shows the current state of your repository in your prompt.

To start with, you need to install the bash-completion package. If you're using Arch Linux it's easily done by invoking:

pacman -S bash-completion

Then, you have to modify the start script for Bash such that the new completion scripts will be used. Open~/.bashrc and add the following lines:

# Bash completion
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi

The only thing which is left is to modify the prompt. Add the following line to the file:

export PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[01;33m\]$(__git_ps1)\[\033[01;34m\] \$\[\033[00m\] '

This will show the username and hostname (green) and the current working directory (blue). Only when you're inside a Git repository, it will show the current branch (yellow). In case you already have a fancy pants prompt, it's a matter of incorporating the __git_ps1 function call.

__git_ps1 does not show whether the repository has pending changes. You can enable this by setting the following variable before the PS1 line:

export GIT_PS1_SHOWDIRTYSTATE=1

This shows a asterisk * whenever there are non-committed changes around. It also shows a plus + for changes which are staged but not yet commited (git add). Please note that entering repositories takes considerably longer than before, because it takes a while to check the repository for pending changes. Usually this is only the first time, the disk cache should speed things up in the future.

When you have modified the PS1 variable, you should reload ~/.bashrc:

source ~/.bashrc

And here's the result:

bram@s000000  (master) <span ;="" font-weight:="" bold;"="" style="color: rgb(0, 0, 255);">$


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值