puppet, ruby, logging and other sysadmin things

This site is built using hugo and the theme is built by Fredrik if you enjoy it, it is available at github

Coloured git status in your bash prompt

After reading a post by Stephen Johnson I decided to reblog it here with some explanation on how to tune it to you liking.

This will give you a coloured bash prompt based on the status of the current git branch you are in. (if you are in one)
This is very handy to make sure things are committed or stashed before switching branches.

Add the following three bash snippets to your .bashrc or .bash_profile

function _git_prompt() {
    local git_status="`git status -unormal 2>&1`"
    if ! [[ "$git_status" =~ Not\ a\ git\ repo ]]; then
        if [[ "$git_status" =~ nothing\ to\ commit ]]; then
            local ansi=32
        elif [[ "$git_status" =~ nothing\ added\ to\ commit\ but\ untracked\ files\ present ]]; then
            local ansi=34
            local ansi=33
        echo -n '\[\e[0;33;'"$ansi"'m\]'"$(__git_ps1)"'\[\e[0m\]'
function _prompt_command() {
  PS1="[\[\033[32m\]\w\[\033[0m\]]\[\033[0m\]\n\[\033[1;36m\]\u@\[\033[0;37m\]\h] `_git_prompt` \[\033[1;33m\]-> \[\033[0m\]"

The key line in the second function is the PS1 variable. This can be constructed any way you want to.
You just need to insert _git_prompt (inside of backticks) at the point you want the coloured git status to appear.

Because you are wanting to effectively run a command inside of your PS1 now (via backticks)
you will need to make sure you are setting this via PROMPT_COMMAND instead of PS1.
This is what the third code block above is for.