Skip to content

Instantly share code, notes, and snippets.

@ogrrd
Last active October 26, 2018 10:00
Show Gist options
  • Save ogrrd/5835005 to your computer and use it in GitHub Desktop.
Save ogrrd/5835005 to your computer and use it in GitHub Desktop.
Git info in your bash prompt

Git info in your bash prompt

Edit ~/.bash_profile and add the following

# git
if [ -f ~/.bash_git ]; then
    . ~/.bash_git
fi

Create ~/.bash_git and add the following

function parse_git_branch {
    git rev-parse --git-dir > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        git_status="$(git status 2> /dev/null)"
        branch_pattern="^# On branch ([^${IFS}]*)"
        detached_branch_pattern="# Not currently on any branch"
        remote_pattern="# Your branch is (.*) of"
        diverge_pattern="# Your branch and (.*) have diverged"
        untracked_pattern="# Untracked files:"
        new_pattern="new file:"
        not_staged_pattern="Changes not staged for commit"

        #files not staged for commit
        if [[ ${git_status}} =~ ${not_staged_pattern} ]]; then
            state=""
        fi
        # add an else if or two here if you want to get more specific
        # show if we're ahead or behind HEAD
        if [[ ${git_status} =~ ${remote_pattern} ]]; then
            if [[ ${BASH_REMATCH[1]} == "ahead" ]]; then
                remote=""
            else
                remote=""
            fi
        fi
        #new files
        if [[ ${git_status} =~ ${new_pattern} ]]; then
            remote="+"
        fi
        #untracked files
        if [[ ${git_status} =~ ${untracked_pattern} ]]; then
            remote=""
        fi
        #diverged branch
        if [[ ${git_status} =~ ${diverge_pattern} ]]; then
            remote=""
        fi
        #branch name
        if [[ ${git_status} =~ ${branch_pattern} ]]; then
            branch=${BASH_REMATCH[1]}
        #detached branch
        elif [[ ${git_status} =~ ${detached_branch_pattern} ]]; then
            branch="NO BRANCH"
        fi

        echo "( ${branch} ${state}${remote})"
    fi
    return
}

Set your prompt to use the new function

Edit ~/.bash_profile and add the following

export PS1="\u@\h:\w \$(parse_git_branch) $ "

Make it happen

Tell your current terminal to use it now

$ source ~/.bash_profile

Thanks

Thanks to Joe Fleming.

@BobClaerhout
Copy link

I had to remove every '#' in the patterns before it worked.
For information: running on linux kubntu.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment