I used the parseGitBranch
function to define the colors. Your function should look like this:
parseGitBranch () {
if ! git rev-parse --git-dir &> /dev/null; then
return
fi
branch="($(git branch --show-current))"
local STATUS
STATUS=$(git status --porcelain)
if [ -n "$STATUS" ]; then
echo -e "\033[38;5;1m $branch" #red
else
echo -e "\033[38;5;34m $branch" #green
fi
}
And you should set PS1
to:
PS1="\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\$(parseGitBranch) \[\033[00m\]\$\n>"
The code above could be inside ~/.bashrc
.
Explanation
The following line will check if current directory is a git project:
if ! git rev-parse --git-dir &> /dev/null; then
return
fi
I've changed your code git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
to git branch --show-current
. That's an easier way to get the current branch name.
Now, if the condition above is true then the function will check the status for the current git directory.
The most effective way to know if there are changes in your project is using git status --porcelain
. So if you don't have any changes the output of git status --porcelain
will be empty.
With -n "$STATUS"
checks if the length of STATUS is nonzero.
If -n $STATUS
is true then the branch color will be red (because you have changes): echo -e "\033[38;5;1m $branch" #red
.
If it's false then the branch color will be green: echo -e "\033[38;5;34m $branch" #green
.
You can check this link for more information about bash colors and formatting. Maybe your terminal doesn't support some formatting or the colors will not be printed correctly.
echo $PS1
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[32m\]$(parseGitBranch) \[\033[00m\]\$\n>
type -a parseGitBranch
I'm not sure if this will show some output.