Add Git Changes to Bash in Ubuntu

For the last few months, I’ve been using Ubuntu for part of my work, because there are programming languages and frameworks that has better tooling support on UNIX based systems. I must admit that I’m starting to enjoy it, but there was one thing I missed desperately –posh-git – an awesome extension adding git status information directly into a Powershell command line.

Powershell posh-git example

Without this tool I was completely lost, I forgot to commit and I misused branches. Nevertheless, I never lost hope that I could find a way around this problem as bash being very configurable.

Finally, I got a solution and it’s a very simple one. You have to edit your ~/.bash_profile and add the following lines.

function parse_git_dirty {
  [[ $(git status 2> /dev/null | tail -n1) != "nothing to commit, working directory clean" ]] && echo "*"
}
 
function parse_git_branch {
  git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/[\1$(parse_git_dirty)]/"
}
 
export PS1='\[\]\w\[\e[0m\] $(__git_ps1 "[\[\e[0;32m\]%s\[\e[0m\]\[\e[1;33m\]$(parse_git_dirty)\[\e[0m\]]")\$ \[\e[0m\]'

Restart the terminal and navigate to one of your repositories. Now, you should see the branch name and an asterix sign to signal whether there are some changes or not.

Bash with git changes

No more forgotten commits!


Would you like to get the most interesting content about programming every Monday?
Sign up to Programming Digest and stay up to date!