bash提示符与上次退出code [英] Bash Prompt with Last Exit Code

查看:119
本文介绍了bash提示符与上次退出code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在试图通过bash提示符定制,使其看起来像

So, I've been trying to customize by 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 运行,结果是永远取代后。这使得名字总是绿色的,即使上次退出code是非零(如,回声$?)。这是发生了什么事?或者它只是别的东西错了我的提示?长的问题总之,如何让我的提示使用上次退出code?

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 are 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 ran after each command to generate the prompt.

您可以尝试以下的〜/ .bashrc中

export PROMPT_COMMAND=__prompt_command  # Func to gen PS1 after CMDs

function __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 line 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提示符与上次退出code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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