Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

linux - Bash prompt with the last exit code

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

[feralin@localhost ~]$ _

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)ue[m@e[1;34mh e[0;35mWe[1;33m]$ e[m

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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}"
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...