sashoalm
sashoalm

Reputation: 79725

Show current branch and coloring on Linux (like Git Bash on Windows)

On Git Bash on Windows I get nice coloring and the current branch is shown, like this:

enter image description here

How can I get the same coloring and prompt on Linux? On Linux I use the regular terminal, which doesn't show the current branch.

Upvotes: 10

Views: 9129

Answers (2)

Arpan Roy
Arpan Roy

Reputation: 61

If you would like to retain the same coloring of your existing linux terminal and also show the current git branch, you can add the following to your default PS1.

PS1 basically tells your bash prompt what to display. Ref: How to Change / Set up bash custom prompt (PS1) in Linux

I am using Ubuntu 20.04 and the default PS1 is found under if [ "$color_prompt" = yes ]; then in the ~/.bashrc file.

Steps:

  1. Open the ~/.bashrc file and find if [ "$color_prompt" = yes ]; then
  2. Define the following bash function (Thanks @Nogoseke) above the if statement (You can define it anywhere above the PS1 value in the file).
#show git branch
show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
  1. Update the PS1 values to the following:
if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]\$(show_git_branch)\[\033[00m\]$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w \$(show_git_branch)\$ "
fi

The entire thing should look something like this:

#show git branch
show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[\033[31m\]\$(show_git_branch)\[\033[00m\]$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w \$(show_git_branch)\$ "
fi
  1. Save the changes and restart your terminal.

It should looks something like this: Terminal with git branch

Upvotes: 6

Nogoseke
Nogoseke

Reputation: 984

If you are using bash,

I use the following on my ~/.bashrc:

show_git_branch() {
   git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
 }
 export PS1="\[\033[0;37m\]\u@\h\[\033[0;37m\] \w \[\033[31m\]\$(show_git_branch)\[\033[00m\]$\[\033[00m\] "

A sample of what it looks like:

enter image description here

You just need to add the code to your .bashrc file and run source ~/.bashrc.

Upvotes: 3

Related Questions