MacOS – Including virtual environment in bash prompt

bashcommand linemacosterminal

I am using bash on MacBook Air running macOS Mojave and wanted to change the color of terminal prompt.

I was helped on this question on SO and this IBM blog after which I used

export PS1="\[\e[30;47m\]\W\[\e[30;47m\]$\[\e[0m\]"

which has colour, wrapping, working directory and $.

It changed the colour but the prompt doesn't have (base) or (ml) in it.
It is the virtual environment I created using conda. conda deactivate removes it. Originally,

$ echo $PS1
(base) \h:\W \u\$           #original prompt with base.

$ conda deactivate          
$ echo $PS1
\h:\W \u\$                  #original prompt with no environment.  

$ conda activate ml
$ echo $PS1
(ml) \h:\W \u\$             #original prompt with ml environment. 

$ export PS1="\[\e[30;47m\]\W\[\e[30;47m\]$\[\e[0m\]"
$ echo $PS1
\[\e[30;47m\]\W\[\e[30;47m\]$\[\e[0m\]    #new prompt with no environment 
                                          #while ml is active   

What can I include to have the (base) or (ml) there, to make it like

$ echo $PS1
(base) \[\e[30;47m\]\W\[\e[30;47m\]$\[\e[0m\]    #expected result.

I didn't find any reference on bash manual for virtual environment under controlling the prompt section.

I need to find where the current active environment is. Either in any file or any command that invokes the env name, which can written in ~/.bash_profile and then add that variable to PS1.

Best Answer

You can activate a virtual environment for conda by running

conda activate base

Replace base with whatever (defined) conda environment you want to use.

pse@Mithos:~$ export PS1="\[\e[30;47m\]\W\[\e[30;47m\]$\[\e[0m\]"
~$cd .tmp
/Users/pse/.tmp
.tmp$conda activate base
((base) .tmp$conda deactivate 
.tmp$