Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make shell prompt show current head when in a VCS

When using a VCS, (I use Mercurial and Git in Linux, Bash prompt), is there any way to have the prompt show the current head or tag in the directory?

More than once I have shot myself in the foot by working in one head when thinking I was in another, for example, pushing v0.3 to testing when they needed v.02, or patching bugs in dev then they needed to be patched in prod, or vice versa.

like image 707
cc young Avatar asked Dec 23 '11 02:12

cc young


People also ask

How do I show a git branch from a bash prompt?

The git_branch() is a function, that prints the name of the current Git branch in the round brackets. We set the PS1 variable and place the function git_branch() inside it to display the Git branch in the terminal prompt. The function inside the PS1 variable must be in the following format: \$(git_branch) .

How do I change the $PS1 prompt in Linux bash?

You can change the BASH prompt temporarily by using the export command. This command changes the prompt until the user logs out. You can reset the prompt by logging out, then logging back in.

How do I show the directory path in UNIX prompt?

By default, bash shows just your current directory, not the entire path. To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd.

Where is __ git_ps1 defined?

It's /etc/git-prompt.sh that defines the __git_ps1 function (Line #273 in my version) is defined. You'll notice that the __git_ps1 function pulls in several other functions defined in /etc/git-prompt.sh .


2 Answers

For Mercurial, there is hg-prompt by Steve Losh. This is an extension for Mercurial that gives you a new hg prompt command. You put a call to this command into your PS1 environment variable:

export PS1='\u in \w`hg prompt "{on {branch}}{status}{update}" 2>/dev/null` $'

to get a prompt like

user in ~/src/project on feature-branch? $

where the ? at the end tells you that there is an unknown file in your repository.

Steve wrote a blog post about his Zsh prompt and there are more colorful prompts from the documentation:

Steve's colorful prompts

like image 111
Martin Geisler Avatar answered Sep 30 '22 20:09

Martin Geisler


Git provides a bash function that shows the current branch or hash if headless. Look for __git_ps1 in the bash_completion file.

My ~/.bashrc contains these lines:

Green='\[\e[0;32m\]'
BIGreen='\[\e[1;92m\]'
Color_Off='\[\e[0m\]'
export PS1=$Green'\w $(__git_ps1 "(%s)")'$BIGreen'$ '$Color_Off

which will create a prompt like this:

~/repos/myproject (master)$ 
like image 33
JRideout Avatar answered Sep 30 '22 18:09

JRideout