Bash Customizing PS1 Show a git branch using PROMPT_COMMAND


Example

If you are inside a folder of a git repository it might be nice to show the current branch you are on. In ~/.bashrc or /etc/bashrc add the following (git is required for this to work):

function prompt_command {
    # Check if we are inside a git repository
    if git status > /dev/null 2>&1; then
        # Only get the name of the branch
        export GIT_STATUS=$(git status | grep 'On branch' | cut -b 10-)
    else
        export GIT_STATUS=""
    fi
}
# This function gets called every time PS1 is shown
PROMPT_COMMAND=prompt_command

PS1="\$GIT_STATUS \u@\h:\w\$ "

If we are in a folder inside a git repository this will output:

branch user@machine:~$

And if we are inside a normal folder:

user@machine:~$