bash prompt and echoing colors inside a function

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.

Leave a Comment