Why are some (often long) commands garbled in bash & zsh

bashshellzsh

Many times when I enter a long command in bash or zsh (these are the only two shells I am positive I have seen this in) the cursor warps to somewhere in the middle of the string I am entering, can anyone explain why this is, and if something can be done about this?

I have noticed that this often happens when I browse the history of my shell (using arrow keys), when I encounter a long entry, the long, new entry will mix up with the previous entry, rendering the text garbled.

I have an example with short strings, which I just noticed:

History contains:

mkdir sune1
mkdir sune2

If I navigate to mkdir sune1, and then to mkdir sune2, I would expect my command line to be mkdir sune2 (since this is what I have now navigated to) – but instead I get mkdir1sune2.

I have noticed this frequently for years, but never let it bother me too much, but I figure it is time for a change! So, any ideas?

Best Answer

Your prompt string probably has incorrectly escaped nonprinting characters. If you have anything like color changes in your prompt, you need to put \[ and \] around the terminal escape sequences so bash can tell that they don't take up space on screen — otherwise it miscalculates where the actual command is on screen, and updates it in the wrong place. See this section from TLDP. In zsh, put %{ and %} around escape sequences.

Related Question