How do I get long command lines to wrap to the next line?

Solution 1:

Make sure all non-printable bytes in your PS1 are contained within \[ \]. Otherwise, bash will count them in the length of the prompt. It uses the length of the prompt to determine when to wrap the line.

For example, here bash counts the prompt as 19 columns wide, while the prompt displayed by the terminal is only 10 columns wide (My prompt written in cyan, and > written in default color):

PS1='\e[36mMy prompt\e[0m>'         # bash count: 19, actual: 10

while here it only counts the prompt as 10 columns wide because it ignores the bytes between the special \[ and \] escapes:

PS1='\[\e[36m\]My prompt\[\e[0m\]>' # bash count: 10, actual: 10

For good practice though, use tput to generate the terminal escapes rather than hard coding them:

cyan=$(tput setaf 6) # \e[36m
reset=$(tput sgr0)   # \e[0m
PS1='\[$cyan\]My prompt\[$reset\]>'

See http://mywiki.wooledge.org/BashFAQ/053, and also http://wiki.bash-hackers.org/scripting/terminalcodes for more on tput.

Solution 2:

I guess you have configured your PS1 with colors, right?

Just make sure you have \[ inside your PS1 quote preceding your color set

For example:

PS1='\[\e[0;32m\u@\w/:\[\e[m '