kill -WINCH $$ to fix bash prompt wrapping to the same line

Sometimes, my bash prompt wraps long lines incorrectly, such that I’m typing over my own prompt like this:

My bash prompt is wrapping long lines onto itself! The horror!

I used to just live with it, trying to remember what I already typed and counting characters if I was going back to change something. That made my Unix experience much more frustrating that it should’ve been, because executing this single command immediately resolved the issue:

kill -WINCH $$

What does this do? You’re basically telling bash that the window size has changed. It turns out that if you resize your terminal window, bash sometimes doesn’t notice the size change without you giving it an extra nudge. Without the correct window size in hand, bash can’t wrap your text correctly!

If that doesn’t solve your bash wrapping woes, then it may be because your prompt format is incorrect. (Yup, I’ve been there, done that.) Do echo $PS1 to see what your prompt is, make changes and test drive your updated prompt by doing export $PS1='your_new_prompt_here', and save the version that makes you proud to be a shell user by putting export $PS1='your_amazing_new_prompt_here' in your ~/.bash_profile. Arabesque has a detailed guide on formatting your prompt, and Fabien Loison has way too much info about adding colour to your prompt.

Have fun at the command line!

  • Ted

    Wow, thanks I have tried switching terminal emulators trying to figure this issue out, and now I know!

  • je

    The most common problem with PS1, that could cause this, is with these two sequences not being used perfectly:

    [ begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
    ] end a sequence of non-printing characters

    These are required so that bash can track the intended cursor position. If PS1 is not perfect, bash will count non-printing characters when moving the cursor, and move it too far out, and it will print misaligned line edits.

    The other way it gets messed up is when a running program intercepts the WINCH signal without passing it (or another one) on to bash after it exits. It may be more complicated than that, I’ve never fixed a program that has this problem. I’ve actually gotten in the habit of working around it by resizing the window again after programs exit, like vim or less, using a keyboard shortcut.