Question

I want to execute a command that writes some dynamic info to my shell prompt. It works fine if I do the coloring statically, because I can just put \[ and \] before and after the escape sentence:

 '\[\e[0;91m\]$(printSomething)\[\e[0m\]'

But if the coloring is dynamic, and I want the external script to print it, then it doesn't work. Now I can't write the escape sequences into the PS1 directly. But if the external script prints \[ and \], then the shell displays it literally.

Is there any way to make it work?

Was it helpful?

Solution

Use the PROMPT_COMMAND to reset PS1 each time you display it. To take your original prompt:

prompt_cmd () {
    PS1='\[\e[0;91m\]'
    PS1+=$(printSomething)
    PS1+='\[\e[0m\]'
}

PROMPT_COMMAND=prompt_cmd

I assume you want some different color. To do that, you could have some environment variable that prompt_cmd reads:

prompt_cmd () {
    PS1="\[\e[0;${PROMPT_COLOR}m\]" # note the double quotes
    PS1+=$(printSomething)
    PS1+='\[\e[0m\]'
}

or you can run some code in prompt_cmd itself that determines which color to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top