5

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?

pkaramol
  • 2,031
  • 5
  • 23
  • 29

2 Answers2

6

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\]$ '
Zanna
  • 69,223
  • 56
  • 216
  • 327
  • 3
    If you use `$PWD` instead of `$(pwd)` the shell doesn't have to set up a pipe, fork two new processes and invoke one external command for every prompt. :-) – David Foerster Apr 25 '17 at 11:22
  • 2
    @DavidFoerster haha thanks! It's a while since I messed with my prompt. The proper PS1 way is to use `\w` but it changes `/home/zanna` into `~` – Zanna Apr 25 '17 at 11:30
  • I know. I wasn't sure either and had to look it up in the manual. – David Foerster Apr 25 '17 at 11:31
2

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

pkaramol
  • 2,031
  • 5
  • 23
  • 29
  • 1
    If you use `$PWD` instead of `$(pwd)` the shell doesn't have to set up a pipe, fork two new processes and invoke one external command for every prompt. Also, you don't need to export `PS1` and it's probably better if you don't. :-) – David Foerster Apr 25 '17 at 11:23
  • @DavidFoerster thanks! I have updated my answer accordingly. – pkaramol Apr 25 '17 at 11:49