【发布时间】:2019-08-12 22:03:35
【问题描述】:
我很难找到一个简洁的答案。我正在使用 Oh My Zsh,现在使用默认主题 robbyrussell。
我希望我的提示有 2 个组成部分:
- 当前目录,再加上一级
- 如果我使用的是虚拟环境(如 anaconda),请将活动环境的名称放在括号中。
【问题讨论】:
我很难找到一个简洁的答案。我正在使用 Oh My Zsh,现在使用默认主题 robbyrussell。
我希望我的提示有 2 个组成部分:
【问题讨论】:
下面是实现方法,你可以根据自己的需要自定义
# Helper method to add background and foreground colors
prompt_segment () {
local bg fg
[[ -n $1 ]] && bg="%K{$1}" || bg="%k"
[[ -n $2 ]] && fg="%F{$2}" || fg="%f"
if [[ $CURRENT_BG != 'NONE' && $1 != $CURRENT_BG ]]
then
echo -n " %{$bg%F{$CURRENT_BG}%}$SEGMENT_SEPARATOR%{$fg%} "
else
echo -n "%{$bg%}%{$fg%} "
fi
CURRENT_BG=$1
[[ -n $3 ]] && echo -n $3
}
prompt_virtualenv () {
# Check if we are in a virtual environment
# if we are then VIRTUAL_ENV variable will be set
local virtualenv_path="$VIRTUAL_ENV"
if [[ -n $virtualenv_path && -n $VIRTUAL_ENV_DISABLE_PROMPT ]]
then
# We are in virtual env so show just the project name
prompt_segment blue black "(`basename $virtualenv_path`)"
fi
}
prompt_directory() {
# Show the current directory
prompt_segment red blue $PWD
}
build_my_zsh_prompt() {
# Call all the prompt functions to build the actual prompt
prompt_virtualenv
prompt_directory
prompt_segment black white ""
}
# Assign the PROMPT variable with the function, so bash call it everytime
# Single quotes are important here, else you will get a fixed PROMPT
# Without single quotes, the function will be called once and evaluated value
# will be assigned
PROMPT='$(build_my_zsh_prompt)'
PROMPT 变量被zsh shell 用来确定需要作为提示显示的内容。当我们设置PROMPT=$(build_my_zsh_prompt)时,我们要求shell调用我们的函数build_my_zsh_prompt。
这个函数反过来(理想情况下)应该调用不同的函数来创建提示的各个部分。现在让我们看看prompt_directory
prompt_segment black red $PWD"
prompt_segment 是一个辅助函数,用于回显一些带有背景和前景色的文本
在这种情况下,第一个参数black 是背景,第二个参数red 是前景色。接下来我们展示需要为这个提示提供什么文本。
所有这些都需要在最后添加到您的~/.zshrc 文件中
【讨论】:
prompt_parent_directory:1: command not found: prompt_segment prompt_directory:1: command not found: prompt_segment build_my_zsh_prompt:4: command not found: prompt_segment 这是有道理的。 prompt_segment() 应该说什么?