5

I added a little bit of shell scripting to my prompt for fun. It alternates the colors of prompt items randomly. I did it purely because a gray screen gets boring after awhile. The following is my prompt in .bash-profile:

function next_hue
{
    color1=$((31 + (++color % 7)))   # set 31 to 30 for dark on light
    color1=$((31 + (++color % 7)))
    PS1="\n\e[0:${color}m[\W]\n\e[0:${color}m[\u]-> $reset" # set 1 to 0 for     dark on light
}

This alternates the color of my prompt. Yay!

The problem is that sometimes the shell will get "stuck." For instance, the shell is usually like this:

directory
[username]->

If I have recently run the docker run command, and I up-arrow into the history, `docker run gets stuck and I end up with this:

directory
[username]->docker run

If I add a new command it stacks on docker run:

directory
[username]->docker runcd /some/path

I have to use ctrl-c or some other such option, and I can't use the docker-run command again unless I type it all out. WHat could be causing this error? I have looked over my prompt quite a bit and I think it is okay, but it was confusing to figure out in the first place.

  • Where do you call next_hue from? – nohillside Sep 26 '15 at 6:02
  • I don't think it is related to your prompt. More likely there is something weird in your ~/.inputrc messing with the command history. – jmhindle Nov 24 '15 at 20:54
2

You're not escaping the non-printing characters in your prompt. See this article, and use "\[" and "\]" around the colors, something like this (untested) for example...

PS1="\n\e[0:\[${color}\]m[\W]\n\e[0:\[${color}\]m[\u]-> $reset"

You may need to tweek that. Like I said, this is untested so I may have inserted a "\]" in the middle of a colour code. For my prompt I do the escaping when I initialise the colour variables:

PS1_FG="\[$(tput setaf 223)\]"  # Prompt foreground colour (223 = pale orange/brown)

For what it's worth, I can highly recommend using tput when you're dealing with control codes. It makes your scripts more portable, and (IMHO) is easier to read.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .