Search code examples
bashgitanacondaps1

How to set PS1 that make both git and conda can show in the bash?


My .bashrc:

# show a short way
shortwd() {
    num_dirs=3
    pwd_symbol="..."
    newPWD="${PWD/#$HOME/~}"
    if [ $(echo -n $newPWD | awk -F '/' '{print NF}') -gt $num_dirs ]; then
        newPWD=$(echo -n $newPWD | awk -F '/' '{print $1 "/.../" $(NF-1) "/" $(NF)}')
    fi
    echo -n $newPWD
}
# show git branch
git_branch() {
   git symbolic-ref HEAD --short
}

export PS1='\n$CONDA_PROMPT_MODIFIER\e[38;5;211m$(shortwd)\e[38;5;48m [$(git_branch)]\e[0m$'

now the bash look like:

(base) /.../MyCode/python [master]$

but after I run conda activate env to switch my conda env. It get a BUG that,whatever command I run ,there always show the current conda env name in the end of command output.like this:

(base) /.../MyCode/python [master]$ls
code_study keras mxnet my_tools other pyqt5 pytorch qt_diankeyuan test windowsCode
(base)

enter image description here

If I want to make the conda env name do not always show in end of the each command output,what should I do? enter image description here


Solution

  • I would suggest letting Conda handle its own part of modifying PS1 and use your nice custom bash functions for the other parts. For this, I would change the PS1 to

    export PS1='\e[38;5;211m$(shortwd)\e[38;5;48m [$(git_branch)]\e[0m$'
    

    and move this to before the Conda-managed section of your .bashrc. Next, set the Conda configuration variable env_prompt to what you want:

    conda config --set env_prompt "\n({default_env}) "
    

    You can read more about the templateable variables in the description conda config --describe env_prompt.

    The only way this deviates from the behavior you defined is that when no envs are active you won't get the extra newline, but hopefully you can live with that. The other downside is that Conda only allows prepending.


    As an aside, your git_branch function is going emit to stderr when not in a repo, so you may want to divert that so it doesn't hit your session. For example,

    # show git branch                                                                                                                                      
    git_branch() {
        git symbolic-ref HEAD --short 2> /dev/null
    }