@ wrote... (2 years ago)

At work we have a large project that is comprised of several nested git repos so having your bash prompt get updated with some vital information such as repo, branch, etc makes life much easier.

Here's an example of my prompt and how it shows the current git repo:

[kurt@machine-1 ~/src/foo/bar/baz venv:foo git:bug_branch repo:bar]

My .bash* files are overly complicated and need a good rototilling, but here are pieces of them in all their glory.

git prompt

Download https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh but save it as ~/.bash_gitprompt. I rename the file so it's easier to copy my environment to a new machine (a proper dotfiles repo is on my todo list). Thanks for this work Shawn O. Pearce.

git repo

create ~/bin/git-repo:

mkdir -p ~/bin
cat > ~/bin/git-repo << EOF
git rev-parse --show-toplevel
chmod +x ~/bin/git-repo

if you run the command git repo it will tell you what repo you're in (or throw a bunch of errors).


add/edit the following to your ~/.bashrc file:

source ~/.bash_gitprompt

function prompt_command_collection() {
    # set xterm title to user@host:path
    printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/\~}"

    # get basename of current git repo (or nothing)
    __repo=$(basename `git repo 2> /dev/null` 2> /dev/null)
    if [ -n $__repo ]; then

    __git_ps1 "[\u@\h \[\e[1;34m\]\w\[\e[0m\]${handle_virtualenv_prompt}" "]\n\\\$ " " git:%s ${__repo}"

# PS1 is overritten by PROMPT_COMMAND but I like it defined anyways
export PS1="[\u@\h \[\e[1;34m\]\w\[\e[0m\]]\n\\$ "
export PROMPT_COMMAND=prompt_command_collection

See Automatically activate virtualenv for information on setting up python virtual environments and the handle_virtualenv_prompt variable. If you use python (you should!) then that post is even more useful than this one.


Anyway, after making all your changes, source ~/.bashrc and then cd into a directory with git repo. Bonus marks if it's also a python virtual environment.

Category: tech, Tags: shell
Comments: 1
Arne Grimstrup @ August 14, 2018 wrote... (3 months, 4 weeks ago)

There is a command in the .bashrc code. The command string git repo 2> /dev/null should be git-repo 2> /dev/null .

Click here to add a comment