带有最后退出代码的Bash提示 [英] Bash prompt with the last exit code

查看:44
本文介绍了带有最后退出代码的Bash提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试自定义我的Bash提示符,使其看起来像

I've been trying to customize my Bash prompt so that it will look like

[feralin@localhost ~]$ _

带有颜色.我设法获得了恒定的颜色(每次看到提示时,颜色都是相同的),但是如果最后一个命令的退出状态为非零,我希望用户名("feralin")显示为红色,而不是绿色.我想出了:

with colors. I managed to get constant colors (the same colors every time I see the prompt), but I want the username ('feralin') to appear red, instead of green, if the last command had a nonzero exit status. I came up with:

\e[1;33m[$(if [[ $? == 0  ]]; then echo "\e[0;31m"; else echo "\e[0;32m"; fi)\u\e[m@\e[1;34m\h \e[0;35m\W\e[1;33m]$ \e[m

但是,根据我的观察,运行 .bashrc 时, $(if ...; fi)似乎被评估一次.之后永远取代.即使最后一个退出代码为非零(例如,在 echo $?中),这也使名称始终为绿色.这是怎么回事吗?还是我的提示仅仅是其他问题?长话短说,如何提示我使用最后一个退出代码?

However, from my observations, the $(if ...; fi) seems to be evaluated once, when the .bashrc is run, and the result is substituted forever after. This makes the name always green, even if the last exit code is nonzero (as in, echo $?). Is this what is happening? Or is it simply something else wrong with my prompt? Long question short, how do I get my prompt to use the last exit code?

推荐答案

当您开始在复杂的 PS1 ,您可以考虑使用 PROMPT_COMMAND .这样,您就可以将其设置为一个函数,并且它将在每个命令之后运行以生成提示.

As you are starting to border on a complex PS1, you might consider using PROMPT_COMMAND. With this, you set it to a function, and it will be run after each command to generate the prompt.

您可以在〜/.bashrc 文件中尝试以下操作:

You could try the following in your ~/.bashrc file:

PROMPT_COMMAND=__prompt_command    # Function to generate PS1 after CMDs

__prompt_command() {
    local EXIT="$?"                # This needs to be first
    PS1=""

    local RCol='\[\e[0m\]'

    local Red='\[\e[0;31m\]'
    local Gre='\[\e[0;32m\]'
    local BYel='\[\e[1;33m\]'
    local BBlu='\[\e[1;34m\]'
    local Pur='\[\e[0;35m\]'

    if [ $EXIT != 0 ]; then
        PS1+="${Red}\u${RCol}"        # Add red if exit code non 0
    else
        PS1+="${Gre}\u${RCol}"
    fi

    PS1+="${RCol}@${BBlu}\h ${Pur}\W${BYel}$ ${RCol}"
}

这应该按照您想要的方式进行.看看我的 bashrc 子文件 如果你想看看我用我的 __prompt_command 函数做的所有事情.

This should do what it sounds like you want. Take a look a my bashrc's sub file if you want to see all the things I do with my __prompt_command function.

这篇关于带有最后退出代码的Bash提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆