linux 如何让conda env和git branch在命令行提示符下运行?

egmofgnx  于 2023-05-16  发布在  Linux
关注(0)|答案(1)|浏览(174)

How to set PS1 that make both git and conda can show in the bash?Bash command prompt with virtualenv and git branch
我已经找到了以下关于如何在bashshell中做到这一点,但我在macosx中使用zsh。这和使用zsh是一样的吗?我的~/.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 <<<

我尝试使用这个链接https://medium.com/pareture/simplest-zsh-prompt-configs-for-git-branch-name-3d01602a6f33,但它不包含git分支信息。有人能扩展一下这个吗?这样git分支信息就包括在内了。

1l5u6lss

1l5u6lss1#

1.关闭conda自动修改命令提示符(PS1)

安装conda后,在终端运行以下命令:

conda config --set changeps1 false

或者简单地将changeps1: false添加到~\.condarc文件中。这将禁用conda对提示符的自动修改。

2.修改提示显示conda env和分支

接下来,打开~\.zshrc,并在文件底部添加以下代码:

# 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.应用更改

在终端中,运行source ~/.zshrc

4.参考资料

修改conda env提示显示设置的原始代码:how to modify the anaconda environment prompt in zsh?
显示git分支的原始代码:Add Git Branch Name to Terminal Prompt

相关问题