2

I am trying to have a function, called from PS1 which outputs something in a different colour, depending on what that something is.

  • In this case it's $?, the exit status of a program.
  • I am trying to get this function to output red text if the exit status is anything other than 0.
  • I have tried all possible variations of this, ways of representing that variable in the conditions and so forth and it just isn't working.

Instead of outputting what I expect it's just either always $LRED in one variation of this IF, or always $HII in another variation of this IF.

All relevant BASH is posted below, can you guys offer any insight?

...

# Custom Colour Alias
NM="\[\033[0;38m\]" # No background and white lines
HI="\[\033[1;36m\]" # Username colour
HII="\[\033[0;37m\]" # Name colour
SI="\[\033[1;32m\]" # Directory colour
IN="\[\033[0m\]" # Command input color
LRED="\[\033[1;31m\]"
BRW="\[\033[0;33m\]"

...

exitStatus ()
{
    if [ $? -ne 0 ]
        then
            echo "$LRED\$?"
        else
            echo "\$?"
    fi
    #echo \$?
}

...

export PS1="\n$HII[ $LRED\u $SI\w$NM $HII]\n[ \! / \# / $(exitStatus) $HII]$LRED $ $IN"

CODE BASED ON SOLUTION

This is what I did based on the accepted answer below.

# Before Prompt
export PROMPT_COMMAND='EXSO=$?;\
    if [[ $EXSO != 0 ]];\
        then\
            ERRMSG="$LRED$EXSO";\
        else\
            ERRMSG="$EXSO";\
    fi;\
PS1="\n$HII[ $LRED\u $SI\W$NM $HII\! / \# / $ERRMSG $HII] $SI$ $IN";'
4

1 回答 1

1

问题是您对 PS1 的分配只被评估一次,因此 exitStatus 只被调用一次。正如 Nirk 还提到的,您应该使用 PROMPT_COMMAND。将其设置为在显示每个新提示之前要执行的命令。一个例子:

PROMPT_COMMAND='if [ $? -ne 0 ]; then echo -n FAIL:;fi'

如果上一个命令失败,将在每个新提示之前大喊 FAIL::

mogul@linuxine:~$ date
Sun Sep 29 21:13:53 CEST 2013
mogul@linuxine:~$ rm crappy_on_existent_file
rm: cannot remove ‘crappy_on_existent_file’: No such file or directory
FAIL:mogul@linuxine:~$ 
于 2013-09-29T19:14:45.890 回答