Bash Prompt with Last Exit Code

后端 未结 7 1746
余生分开走
余生分开走 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 22:44

    To preserve original prompt format (not just colors), you could append following to the end of ~/.bashrc:

    PS1_ORIG=$PS1 # original primary prompt value
    PROMPT_COMMAND=__update_prompt # Func to be re-evaluated after each command is executed
    __update_prompt() {
        local PREVIOUS_EXIT_CODE="$?"
        if [ $PREVIOUS_EXIT_CODE != 0 ]; then
            local RedCol='\[\e[0;31m\]'
            local ResetCol='\[\e[0m\]'
            local replacement="${RedCol}\u${ResetCol}"
    
            # Replace username color
            PS1=${PS1_ORIG//]\\u/]$replacement}
            ## Alternative: keep same colors, append exit code
            #PS1="$PS1_ORIG[${RedCol}error=$PREVIOUS_EXIT_CODE${ResetCol}]$ "
        else
            PS1=$PS1_ORIG
        fi
    }
    

    See also the comment about the alternative approach that preserves username color and just appends error code in red to the end of original prompt format

提交回复
热议问题