Your Bash Prompt Needs This

Have you ever had this happen to you? You start a program and then interrupt it with Ctrl-C, and Bash prints its prompt after the ^C you have typed:

prompt$ a very long command
^Cprompt$ █

Then you hit the Up key to retrieve very long command from the history and try to edit it, only to discover that the text you see on the screen is shifted by two characters from where it appears to be, and you can’t see where you’re typing anymore. A major annoyance!

Here’s how you can fix it: make the prompt go to the first column always. To do this, include \033[G in your $PS1:

PS1="\[\033[G\]$PS1"

This code happens to be the ANSI escape code for moving the cursor to the first column. Your prompt will now start from the first column and write over the ^C you typed. The \[ and \] on the other hand are needed so that Bash does not count these movement codes when calculating the length of the prompt.

The Bash Prompt HOWTO is a great resource if you want to learn more about how and why to customize your prompt.

Update: Wow, I never expected this would spark such a lively discussion on Hackernews! People there suggest many alternative solutions to this problems, such as simply hitting Ctrl-C or Enter to get a clean line whenever this occurs, configuring a two-line prompt, or ditching Bash for Zsh.

A penny for your thoughts

(Your email is never shared.)