bash prompt and echoing colors inside a function

Viewed 20192

I have this in my .bashrc:

LIGHTGREEN="\[\033[1;32m\]"
LIGHTRED="\[\033[1;31m\]"
WHITE="\[\033[0;37m\]"
RESET="\[\033[0;00m\]"

function error_test {
    if [[ $? = "0" ]]; then
        echo -e "$LIGHTGREEN"
    else
        echo -e "$LIGHTRED"
    fi
}

PS1="\u\$(error_test)@\w$RESET \$ "

This seems to make the shell output exactly:

username\[\]@~/

The escaping [ and ] around the color codes are showing up in my prompt. If I remove the escape codes from around the colors it works, but then bash line wrapping fails stupendously.

Note if do PS1="LIGHTGREEN - whatever - $RESET" it works and the [ and ] are not escaped. However, I want to do this inside a function, which seems to be the issue.

I can't find any good documentation on this. man echo doesn't even list a -e option. Bash seems like it has a lot of undocumented, handmedown knowledge.

6 Answers
Related