Bash Prompt with Last Exit Code

后端 未结 7 1733
余生分开走
余生分开走 2020-11-30 22:12

So, I\'ve been trying to customize by bash prompt so that it will look like

[feralin@localhost ~]$ _

with colors. I managed to get constant

7条回答
  •  無奈伤痛
    2020-11-30 23:06

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

    You could try the following in your ~/.bashrc

    PROMPT_COMMAND=__prompt_command # Func to gen 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 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.

提交回复
热议问题