• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

bash提示符和上次退出code

用户头像
it1352
帮助1

问题说明

所以,我一直在试图通过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?

正确答案

#1

由于是正开始在一个复杂的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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhaig
系列文章
更多 icon
同类精品
更多 icon
继续加载