Search code examples
bashfunctioncolorsecho

bash prompt and echoing colors inside a function


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.


Solution

  • I found this topic looking for answer how to set bash color with escaping \[ \] from bash function.

    Actually there is solution. Bash allows to generate PS1 prompt each time prompt is rendered.

    set_bash_prompt(){
        PS1="\u@\h $(call_your_function) $>"
    }
    
    PROMPT_COMMAND=set_bash_prompt
    

    This way, PS1 will be interpreted each time prompt will be displayed, so it will call function and render properly all escaping sequences including \[ \] which are important for counting length of prompt (e.g. to make command history work correctly).

    Hopefully this will help someone, as I spend half a day to solve this issue.