How to have both conda env and git branch within command line prompt?
Asked Answered
J

1

6

How to set PS1 that make both git and conda can show in the bash? Bash command prompt with virtualenv and git branch

I've found the following about how to do this in bash shell but i'm using zsh within macosx. Would this work the same way using zsh? I have the following in my ~/.zshrc

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/carlos/opt/anaconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/blah/profile.d/conda.sh" ]; then
        . "/blah/opt/anaconda3/etc/profile.d/conda.sh"
    else
        export PATH="/blah/opt/anaconda3/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

I tried using this link, https://medium.com/pareture/simplest-zsh-prompt-configs-for-git-branch-name-3d01602a6f33, but it doesn't contain the git branch information. Could someone expand on this so the git branch info is included?

Julianejuliann answered 24/3, 2022 at 18:28 Comment(0)
S
2

1. Disable automatic modification of the command prompt (PS1) by conda

With conda already installed, run the following command in the termial:

conda config --set changeps1 false

or simply add changeps1: false to the ~\.condarc file. This will disable the automatic modification of the prompt by conda.

2. Modify prompt to display conda env and branch

Next, open ~\.zshrc with any text editor, and add the following code at the bottom of the file:

# Determines prompt modifier if and when a conda environment is active
precmd_conda_info() {
  if [[ -n $CONDA_PREFIX ]]; then
      if [[ $(basename $CONDA_PREFIX) == "anaconda3" ]]; then
        # Without this, it would display conda version. Change to miniconda3 if necessary
        CONDA_ENV="(base) "
      else
        # For all environments that aren't (base)
        CONDA_ENV="($(basename $CONDA_PREFIX)) "
      fi
  # When no conda environment is active, don't show anything
  else
    CONDA_ENV=""
  fi
}

# Display git branch
function parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}

# Run the previously defined function before each prompt
precmd_functions+=(precmd_conda_info)

# Define colors
COLOR_CON=$'%F{141}'
COLOR_DEF=$'%f'
COLOR_USR=$'%F{247}'
COLOR_DIR=$'%f'
COLOR_GIT=$'%F{215}'

# Allow substitutions and expansions in the prompt
setopt prompt_subst

PROMPT='${COLOR_CON}$CONDA_ENV${COLOR_USR}%n ${COLOR_DIR}%1~ ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}$ '

3. Apply changes

In the terminal, run source ~/.zshrc

4. References

Original code to modify conda env prompt display settings: how to modify the anaconda environment prompt in zsh?

Original code to display git branch: Add Git Branch Name to Terminal Prompt

Serriform answered 16/5, 2023 at 0:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.