Bash Prompt – Abbreviate Current Directory Including Dot Files

bashprompt

I have the following in my .bash_profile (from a similar question here:

PROMPT_COMMAND='pwd2=$(sed "s:\([^/]\)[^/]*/:\1/:g" <<<$PWD)'
PS1='\u@\h:$pwd2\$ '

However, if the current directory is within a .dir (such as ~/.vim/bundle/) then the prompt just displays a .:

chris@DeathStar:/U/c/./bundle$

I would like it instead to retain 1 char for all dirnames unless it has a dot, in which case it would show two, like this:

chris@DeathStar:/U/c/.v/bundle$

Even better would be if I also have the home directory represented by a ~ like this:

chris@DeathStar:~/.v/bundle$

Any ideas?

Best Answer

This seems to do the trick, adding an optional . to the capture:

PROMPT_COMMAND='pwd2=$(sed "s:\(\.\?[^/]\)[^/]*/:\1/:g" <<<$PWD)'
PS1='\u@\h:$pwd2\$ '

And for the 'even better':

PROMPT_COMMAND='pwd2=$(sed -e "s:$HOME:~:" -e "s:\(\.\?[^/]\)[^/]*/:\1/:g" <<<$PWD)'
PS1='\u@\h:$pwd2\$ '
Related Question