Shell prompt customization and cmd behavior

I want my prompt to display:

  1. current (absolute) working directory, colored in green and

  2. in a NEW line, the dollar sign and an empty space.

I am using this line in .profile

export PS1='\e[0;32m$(pwd)\n\e[m$ '

So when in e.g. Desktop, my prompt looks like this:

However, sometimes when hitting the up arrow to re-run previous commands, at the start of the prompt a random char sequence appear that does not seem to go away unless I hit enter, e. g.

I have never hit a cd cd Desktop command. The weirdest part is that backspace won't even delete the first one of the two cd commands above!

Any suggestions?


You must make sure the non-printing characters in the prompt are in escaped square brackets, otherwise bash cannot calculate the size of the prompt correctly. I think I have fixed it for you:

PS1='\[\e[0;32m\]$PWD\n\[\e[m\]$ '

First of all a big thanks to @Zanna for pointing out the correct way to go about this.

For the sake of a more complete answer I have expanded the solution that includes:

a) the cwd in green color

b) in a NEW line, the git branch (if any) in a yellowish color with a red star if the branch is dirty

To accomplish b, the git aware prompt is necessary

It goes something like this as a final line in ~/.bashrc

export PS1='\[\e[0;32m\]$PWD\n\[\e[m\]\[\e[0;33m\]$git_branch\[\e[m\]\[$txtred\]$git_dirty\[$txtrst\]$ '

The prompt will now hopefully expand to sth like this if you are on a git branch

enter image description here