Strovent SystemsSign in
Reference

Bash prompt wraps onto the same line: mark color codes in PS1

Long commands wrap back over the bash prompt when PS1 has color codes outside \[ and \]. Wrap each escape sequence in \[ \] so readline counts the prompt right.

When a long command line wraps back to the start of the same line and types over your prompt, or pressing Up shows bits of old commands that do not go away, the usual cause is color codes in the prompt that are not marked as invisible.

Why it happens

The shell's line editor (readline, in bash) must know how wide the prompt is so it can tell where the cursor is and when the line reaches the right edge. It counts every character in PS1. A color code such as \e[32m takes no space on the screen, but readline counts its characters unless you mark them.

The prompt then looks longer to readline than it is. Readline expects the right edge sooner than it comes, and its cursor moves go to the wrong columns: the text wraps early by returning to the start of the same line, and edits or history recall can leave characters behind.

The fix: put every escape sequence inside \[ and \]

In bash, \[ starts a run of non-printing characters and \] ends it. Wrap each color or title sequence, and nothing else:

PS1='\[\e[1;32m\]\u@\h\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '

Text you can see (\u@\h, \w, \$) stays outside the brackets. If visible text ends up inside, readline counts the prompt as too short, and wrapping goes wrong the other way.

The same applies to sequences made by tput:

PS1='\[$(tput setaf 2)\]\u@\h\[$(tput sgr0)\]\$ '

And to a window-title sequence at the start of the prompt:

PS1='\[\e]0;\u@\h: \w\a\]\u@\h:\w\$ '

Brackets only work when they are typed into PS1 itself. A function or command substitution that prints \[ returns the literal characters. Build the colors into PS1, or set PS1 from PROMPT_COMMAND, which bash runs before it prints the primary prompt:

set_prompt() {
  PS1='\[\e[32m\]\u@\h\[\e[0m\]\$ '
}
PROMPT_COMMAND=set_prompt

zsh uses %{ and %}

In zsh, wrap escape sequences in %{ and %}, or use zsh's own color escapes %F{...} and %f instead of raw codes, so there is nothing to mark:

PROMPT='%F{green}%n@%m%f %~ %# '

Test the result

Type a command longer than the window is wide. It should continue on the next screen line, under the prompt, not over it. Then press Up and Down through a few commands; nothing should be left over.

If the prompt is right and wrapping is still wrong

Then the shell is using the wrong window width. That happens after you resize the window while a full-screen program runs, on a serial console, or in a session that never got the size. Run stty size and compare it with what you see. See Terminal size wrong after resize: stty size, resize and COLUMNS.

A screen left in a strange state after a program crashed is a different problem; see Fix a terminal full of garbage after printing a binary file.

Sources

Spotted a mistake? Email [email protected].