Git prompt with conda and conda-auto-env
The Git Team maintains a bash script that sets a message in your prompt displaying the current branch and status. The script can be found here. To install the script, I have modified the instructions from this tutorial to make it work with conda and the conda-auto-env tool.
First, we are going to assume that conda is install in our system and we will add conda-auto-env. This tools automatically activates the conda environment every time we cd
into a folder that has a env.yml
or environment.yml
files. There are many versions but in this post I will use the one from here modified for bash. Download the file conda_auto_env.sh
to any location in your home folder, for instance ~/scripts
. Then download the script git-prompt.sh
to the same location and add the following to the end of your ~/.bashrc
file:
Let us explain what the previous code does:
- Define colors to use for prompt, this will make the
PS1
variable easier to modify - Define a function
git_and_conda_prompt
. We get the git status from__git_ps1
(provided bygit-prompt.sh
) and color the name of the repository according to the status:*
unstaged files$
stashed files%
untracked files+
uncommited files
- Build the
PS1
variable, this line can be customized by changing the information and colors:$CONDA_PROMPT_MODIFIER
, current conda environment\u
: username\h
: hostname\w
: working directory
- Add
conda_auto_env
(provided byconda_auto_env.sh
) andgit_and_conda_prompt
to the$PROMPT_COMMAND
variable. This variable will be executed just before displaying the prompt. The order is important, since we want to activate the environment first (if any) and then display the prompt with all the information.
The variable $CONDA_PROMPT_MODIFIER
is set by conda activate
and contains the name of the current environment between ()
. conda init
already shows this information in the prompt by setting the PS1
variable, however we have to add it manually to since we are overriding PS1
in the function git_and_conda_prompt
.