如何使我的 zsh 提示看起来像 sh/bash 以 $ 而不是 % 结尾?

How do I make my zsh prompt look like sh/bash end with $ instead of %?

任何人都可以展示如何修改以下 zsh 提示环境 var 分配以使其发出的字符串以 $ 结尾(后跟 space),而不是 %

export PROMPT='%F{111}%m:%F{2}%~ %#%f '

macOS Catalina 将默认 shell 更改为 zsh,我看到了一篇鼓励切换的文章。我假设向后兼容,但提示逻辑发生了变化。

export PROMPT='%F{111}%m:%F{2}%~ $%f '

有关 zsh 提示字符串自定义的更多选项 - http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Login-information

简答:使用%(!.#.$)


长答案:

生成 % 的提示字符串部分是 %# -- 如果 shell 是特权(root)[=56],则生成 # =],否则 %

如果您仍然想要一般的 class 行为,只需使用 $ 而不是 %,您可以用 %(!.#.$) 代替 %# .这是一个条件语句,分为三部分(每部分用.分隔):!检查shell是否有特权,#是检查的扩展值返回true,$为false时的展开值

演示会话(在 shell 中,开始提示只是 % (PROMPT='%% ')):

% PROMPT=': %#; '          ;: # the default %# (unwanted %, just to show it)
: %; sudo -s               ;: # prompt is % now -- until we switch to root
: #; exit                  ;: # prompt is # now -- exit to return to user
: %; PROMPT=': %(!.#.$); ' ;: # set new prompt string with conditional for #/$
: $; sudo -s               ;: # prompt is $ now -- what we wanted
: #; exit                  ;: # prompt is # for root shells, still
: $;                       ;: # back to user shell, prompt back to $

将此折叠到您之前的设置中,我们有:

export PROMPT='%F{111}%m:%F{2}%~ %(!.#.$)%f '

应该成功!




(作为一个随机的旁注,我使用 ; 和内置的 : 命令在可能不允许的地方影响评论——并且在特别是,将提示本身视为注释,因此它可以 copy/pasted 连同重新 运行 命令的命令 - 以 shell 中的一些噪音为代价你粘贴它。此外,上面的示例假设 sudo 最近已经 运行,and/or 被配置为不需要密码——当然,如果需要,这一切仍然有效,在这个例子中它只是额外的噪音。)