Skip to content

Instantly share code, notes, and snippets.

@RyanMillerC
Last active April 20, 2018 18:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanMillerC/940462fe51b87a8604d4314c64348535 to your computer and use it in GitHub Desktop.
Save RyanMillerC/940462fe51b87a8604d4314c64348535 to your computer and use it in GitHub Desktop.
Add git branch and status to end of command prompt while inside a git directory
#!/bin/bash
#
# Created: 2017-07-02 22:44
# Updated: 2018-04-17 10:38
# Creator: Ryan Miller
# Website: http://devopsmachine.com/
# File: ~/.bashrc (Add to file)
#
# Add git information to end of yor bash command prompt while inside a git directory!
# + Will show current branch as either green (clean) or yellow (uncommited changes)
#
# Example: http://devopsmachine.com/img/show-git-status-in-prompt-example.png
#
# Instructions for use: Edit either ~/.bashrc (or ~/.bash_profile). Replace the PS1 line
# with the code below.
RED="\[\e[0;31m\]"
GREEN="\[\e[0;32m\]"
YELLOW="\[\e[0;33m\]"
BLUE="\[\e[0;34m\]"
COLOROFF="\[\e[0;m\]"
get_git() {
local branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/\1/")
if [[ $branch != "" ]] ; then # If in git directory
if [[ $(git status) != *'nothing to commit'* ]] ; then # Dirty directory
local gitstat="${YELLOW}(${branch}*)"
else # Clean directory
local gitstat="${GREEN}(${branch})"
fi
fi
printf "${gitstat}"
}
# Prompt - Based off this: https://gist.github.com/henrik/31631
function git_prompt {
local pyenv=${VIRTUAL_ENV:+(}${VIRTUAL_ENV##*/}${VIRTUAL_ENV:+)}
local ps1="${GREEN}[\u][\h]${BLUE}[\W]"
local gitstat=$(get_git)
local end="${COLOROFF}$ "
PS1="${pyenv}${ps1}${gitstat}${end}" # Prompt up to the git branch
}
PROMPT_COMMAND="git_prompt"
@RyanMillerC
Copy link
Author

Now uses bash builtin PROMPT_COMMAND. This is faster than the subshell inside PS1 previously implemented.

@RyanMillerC
Copy link
Author

Added support for showing sourced python virtualenv.

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