Creating a Bash command prompt with a red $ after failure of previous command

后端 未结 3 672
情书的邮戳
情书的邮戳 2021-01-13 06:03

I\'m new to Bash programming, and I\'m working on creating a custom Bash command prompt. My goal is to create a prompt which only shows the login name and h

3条回答
  •  無奈伤痛
    2021-01-13 06:40

    Use the PROMPT_COMMAND variable, which is executed before each primary prompt according to the bash man page.

    For example (this doesn't work yet, I'm trying to get it working right, but I think it's possible):

    PROMPT_COMMAND="if [ \$? = 0 ]; then DOLLAR="${WHITE}\$${NORMAL}"; else DOLLAR="${RED}\$${NORMAL}"; fi"
    

    Edit: due to frustrations with executing commands and nonprinting characters inside PS1 (the \[ and \] sometimes get printed out literally instead of used as hints to PS1), I've come up with this (replace ... with whatever you want in your prompt):

    PROMPT_COMMAND='if [ $? = 0 ]; then DOLLAR_COLOR="\033[0m"; else DOLLAR_COLOR="\033[31m"; fi'
    PS1='...\[$(echo -ne $DOLLAR_COLOR)\]$\[\033[m\] '
    

    Of course, using $() you could put whichever parts of this you like inside PS1 instead of using PROMPT_COMMAND, I just like it this way so that PROMPT_COMMAND contains the logic and PS1 contains the display commands.

提交回复
热议问题