Tim Randall
Tim Randall

Reputation: 4145

How to add the current git branch to the existing bash prompt

I'm trying to modify my bash prompt to include the current git branch. This is complicated by the fact that there is already a set of rules that determines what the prompt might be - whether it includes color text, whether the user is on xterm etc. ... so what I really want is to be able to combine the string representing the git branch, colors and all, with the previously set prompt.

But I can't even get the most basic implementation to work. The following includes several of my attempts as I try to simplify the script to eliminate possible problems.

# Add current git branch, if any
parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

#PS1="\[\e[34m\]\$(parse_git_branch)\[\e[00m\]$PS1 "
#PS1 = "\$(parse_git_branch) $PS1 "
#PS1 = "\$(parse_git_branch) "
#PS1 = "$(parse_git_branch) "
PS1 = $(parse_git_branch)

Essentially they all produce the same message: PS1: command not found

I'm sure I am missing something simple. Can anyone tell me what it is?

Upvotes: 1

Views: 3902

Answers (2)

l0b0
l0b0

Reputation: 58768

In case you're willing to use an existing solution, there's a Git prompt function already included in many Linux distros. How to use:

PS1=…'$(__git_ps1 " (%s)")'…

The mixed quotes are intentional, and the single quotes are necessary to make this run every time the prompt is displayed. Replace the ellipses with the rest of the prompt, such as '\$ '. If __git_ps1 isn't available out of the box see the full code for a cross-platform solution (works on at least Ubuntu and Arch Linux; should work on recent NixOS).

The " (%s)" part is the format string, that is, a space, open parenthesis (because I want to keep this info separate from the rest of the prompt), the prompt string, and close parenthesis. The %s is replaced by a repository state string, by default just the branch name. See the source code for options and their meanings.

Upvotes: 1

hexbioc
hexbioc

Reputation: 1606

The error you get is because of the spaces surrounding =, as bash attempts evaluates PS1 as a command, and fails.

You can fix it by just removing the spaces. Here is a sample prompt that prints the current user and directory, along with the prompt:

export PS1='[\u@\h] \W :: $(parse_git_branch)> '

Note the single quotes - if you instead use double quotes, the parse_git_branch will be evaluated and will not update on every prompt. As an alternative to single quotes, you can escape the $ if you prefer.

If you want to update your existing prompt to also have the git branch, you can print the current value of the PS1 environment variable and modify it to suit your needs, finally adding the modified version in say your .bashrc file.

Upvotes: 2

Related Questions