Bash – Abbreviated current directory in shell prompt

bashprompt

vim has a really nice feature which it utilizes in its paths when they're a bit long:

enter image description here

It abbreviates the path to the document in the tab at the top. Is there a way to do something similar to this so my bash prompt doesn't look like this:

rfkrocktk@work-laptop ~/Documents/Projects/Work/maventest/src/main/java/com/tkassembled/ $ 

Best Answer

Try this:

PROMPT_COMMAND='PS1X=$(perl -pl0 -e "s|^${HOME}|~|;s|([^/])[^/]*/|$""1/|g" <<<${PWD})'

or, pure bash:

PROMPT_COMMAND='PS1X=$(p="${PWD#${HOME}}"; [ "${PWD}" != "${p}" ] && printf "~";IFS=/; for q in ${p:1}; do printf /${q:0:1}; done; printf "${q:1}")'

then

PS1='\u@\h ${PS1X} $ '

produces (notice the ~ for ${HOME}):

rfkrocktk@work-laptop ~/D/P/W/m/s/m/j/c/tkassembled $

I improved my answer thanks to @enzotib's

Related Question