自定义 zsh 在显示上一个命令退出代码时的提示

发布于 2024-10-08 00:49:17 字数 314 浏览 0 评论 0原文

Zsh 能够使用 %? 转义序列在提示中显示上一个命令的返回代码/退出代码。

但是我希望有以下提示:

user@host ~ [%?] %

当退出代码不同于 0 时和:

user@host ~ %

当退出代码为 0 时。

如果我单独使用 %? 它总是显示,即使 % ? 为 0。 另外,我想要方括号,但只有当退出代码不为 0 时。

最简单的方法是什么?

Zsh includes the ability to display the return code/exit code of the previous command in the prompt by using the %? escape sequence.

However I would like to have the following prompt:

user@host ~ [%?] %

when the exit code is different from 0 and:

user@host ~ %

when exit code is 0.

If I use %? alone it is always displayed, even if %? is 0.
In addition I want the square brackets but only when the exit code not 0.

What is the simplest way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉酒的小男人 2024-10-15 00:49:17

将其添加到 PS1 中您希望退出代码出现的位置:

%(?..[%?] )

它是一个条件表达式。如果第一个点之前的表达式为真,则输出两个点之间的部分(在本例中没有任何内容)。如果为 false,则输出第二个点之后的部分。

例如:

PS1='%n%m %~ %(?..[%?] )%# '

Add this in the position in PS1 where you want the exit code to appear:

%(?..[%?] )

It's a conditional expression. The part between the two dots (nothing in this case) is output if the expression before the first dot is true. The part after the second dot is output if it's false.

For example:

PS1='%n%m %~ %(?..[%?] )%# '
萌面超妹 2024-10-15 00:49:17

或者,您可以:

setopt PRINT_EXIT_VALUE

始终打印显示先前返回值的换行符。

我不喜欢将其用于普通用途,但它对于调试 shell 脚本通常很有用。

Alternatively, you can:

setopt PRINT_EXIT_VALUE

to always print a newline showing previous return value.

I don't prefer this for ordinary use, but it is often good for debugging shell scripts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文