Weird line wrapping in terminal with a colored prompt

bashterminal

I have reason to think I've got improper escaping in my bash prompt (I get weird random line wrapping in Terminal).

Can anyone point it out? It looks OK to me…

export PS1="\033[0;35m\u\033[00m on \033[0;36m\h\033[00m in \033[0;33m\w\033[00m \$ "

Best Answer

Encase your colors in brackets [] so they count as non-printable characters.

export PS1="\[\033[0;35m\]\u\[\033[00m\] on \[\033[0;36m\]\h\[\033[00m\] in \[\033[0;33m\]\w\[\033[00m\] \$ "

Unfortunately, this results in well-known line wrapping issues that is plagued by bash.

There is good news everyone, the light at the end of the tunnel is tput.

echo $(tput setaf 6) This is cyan

Set all your variables first, then use it within the script.

mg=$(tput setaf 5);cy=$(tput setaf 6);yl=$(tput setaf 3);rs=$(tput sgr0); echo $mg $USER $cy $HOSTNAME $yl $PWD $rs

You can find an example script in my github dotfiles repo