Last Updated: February 25, 2016
· macioosch

Shorten /path/to/current/dir in your $PS1 to /p/t/c/dir

I've seen a similar feature in the ranger file manager and I wanted it in my command prompt, here's how I've done it.

I wrote a bash function (mostly a perl regexp, put it in your .bashrc):

shortpath() {
    echo ${@/$HOME/\~} | perl -pe 's,(/[^/])[^/]+(?=/),\1,g'

You may use it like:

PS1='$(shortpath "$PWD")\$ '

Example effect with the $PS1 above:

~$ cd my/folder/tree/
~/m/f/tree$ cd /opt/Amnesia/core/

For utf-8 you can use a longer version:

shortpath() {
    echo ${@/$HOME/\~} | perl -pe 'BEGIN{ binmode(STDIN,":utf8"); binmode(STDOUT, ":utf8")} s,(/[^/])[^/]+(?=/),\1,g'