gpt4 book ai didi

shell - zsh 不重新计算我的 shell 提示

转载 作者:行者123 更新时间:2023-12-03 21:26:00 26 4
gpt4 key购买 nike

这可能有点边缘,但我最近搬到了 zsh 并且在自定义我的 shell 提示时遇到了问题。

我的 .zshrc 的一部分看起来像这样:

# keeping this simple right now by just printing the date, but imagine this function would look for something specific when moving to a new directory each time
function parse_special {
print $(date)
}

autoload -U colors && colors
PS1="%{$fg[green]%}%n@%m %{$fg[blue]%}%c %{$fg[yellow]%}%{$(parse_special)%} %{$reset_color%}%# "

当我启动终端时,一切看起来都很好;我的提示是我所期望的:
me@someHost ~ Wed Aug 8 22:56:22 PDT 2012 %

但是当我 cd 到另一个目录时,似乎没有再次调用我的 parse_special 函数来重新计算我的自定义提示(注意日期没有改变):
me@someHost ~ Wed Aug 8 22:56:22 PDT 2012 % cd .ssh 
me@someHost .ssh Wed Aug 8 22:56:22 PDT 2012 % cd ../workspace
me@someHost workspace Wed Aug 8 22:56:22 PDT 2012 %

有什么办法可以告诉 zsh 在每次要显示提示时重新计算它吗?

非常感谢您的任何建议。

回复 cjhveal

似乎 PS1 不喜欢由单引号值设置。我尝试了以下方法:
local tp1="%{$fg[green]%}%n@%m%{$reset_color%}"
PS1="${tp1}"
print "PS1 set by tp1: ${PS1}"
local tp2='%{$fg[green]%}%n@%m%{$reset_color%}'
PS1="${tp2}"
print "PS1 set by tp2: ${PS1}"

并得到这个输出
#inner stuff was green
PS1 set by tp1: %{%}%n@%m%{%}
#everything was uncolored
PS1 set by tp2: %{$fg[green]%}%n@%m%{$reset_color%}

我还应该补充一点,根据 cjhveal 的建议,这是我真正尝试过的。同样,单引号似乎把事情搞砸了
function parse_special {    
print $(date)
}

autoload -U colors && colors
local prompt_user='%{$fg[green]%}%n@%m%{$reset_color%}'
local prompt_root='%{$fg[red]%}%n@%m%{$reset_color%}'
local prompt_dir='%{$fg[blue]%}%c%{$reset_color%}'
local prompt_special='%{$fg[yellow]%}%{$(parse_special)%}%{$reset_color%}'
PS1="${prompt_user} ${prompt_dir}${prompt_special}%# "

最佳答案

我在 zsh 中自定义我的提示时遇到了同样的问题.

我相信这是因为 shell 在初始化提示时将值插入字符串一次。随后的重新加载在您的提示中具有常量字符串,而不是子 shell 插值。

相反,将任何涉及子 shell 的行放入用单引号定义的变量中。然后插入该变量。

autoload -U colors && colors

local parse_special='%{$fg[yellow]%}$(date)%{$reset_color%}'

PS1="%{$fg[green]%}%n@%m %{$fg[blue]%}%c ${parse_special} %# "

更新:从 ZyX 的答案中添加此内容以为此提供完整的解决方案。您还需要添加以下内容:
setopt promptsubst

事实上,我建议将提示的每个部分提取到这样的变量中,包括每个部分的 reset_color。这样做可以让您更改提示组件的顺序,而无需更改它们的实现。

关于shell - zsh 不重新计算我的 shell 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11877551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com