Search code examples
windowsgit-bashpromptminiconda

Conditional prompt in Git Bash (Windows), with miniconda


I am using git bash on windows 10 with miniconda for my python environments, and I've been trying to modify my prompt to show the environment name. So I have my ~/.bashrc file, where I tried to write a very simple condition inspired from the git-prompt.sh. The result I want is the following:

user@laptop: working_dir (git_branch)
>

and

user@laptop: working_dir (git_branch)
(conda_env) >

when I activate an environment. My problem is that I can't find a way to show the (conda_env) properly. I've tried something like this for the 2nd line:

PS1="$PS1"'\n'                 # new line
    if [ ! -z "$CONDA_DEFAULT_ENV" ]
    then
        PS1="$PS1""($CONDA_DEFAULT_ENV) "
    fi
PS1="$PS1"'\[\033[32m\]'       # change to green
PS1="$PS1"'> '

I also tried different test for the condition, such as:

if [[ "$CONDA_DEFAULT_ENV" != "" ]]
if [ test -n "$CONDA_DEFAULT_ENV"]

and a few others. But I always have problems, sometimes it's the parentheses who show up even when $CONDA_DEFAULT_ENV is null, sometimes the test seems to work but I still have a stray space before the final ">" (which would logically come from the "($CONDA_DEFAULT_ENV) " part, meaning the test is not correct), etc.

Does anyone knows why this happens and how I can have this simple conditional prompt working?


Solution

  • I had the same problem just 2 hours ago, finally, I just found a solution!

    The solution is to encapsulate your if statement inside a function and calling it via the string this way it's dynamic and changes when you change environments.

    Let me show you how I did it:

    check_conda_env ()
    {
        if [ ! -z "$CONDA_DEFAULT_ENV" ]; then
            printf "($CONDA_DEFAULT_ENV) "
        else
            printf ""
        fi
    }
    
    PS1="$PS1"'\n'                 # new line
    PS1="$PS1"'$(check_conda_env)' # calls check_conda_env everytime it is printed to the screen
    PS1="$PS1"'\[\033[32m\]'       # change to green
    PS1="$PS1"'> '
    

    The reason why this works is simply because your string is now "dynamic", meaning it calls the function check_conda_env every time it is printed to the screen.