Smart way to shorten the current working directory in pure Bash
Returning values by variable is 3-10 times faster than capturing an echo with $( ).  Your temp variable is already global.  Just name it something similar to what the surrounding function is named. 

Whitespace and comments affect bash performance negatively.  It's not a big penalty, just something to be aware of.

A regular expression can do the "last two path components" extraction very compactly. 

cwd() {
  cwd=$PWD
  [[ $cwd/ == $HOME/* ]] &amp;&amp; cwd=~${cwd#$HOME}
  [[ $cwd =~ ./([^/]+/[^/]+)$ ]] &amp;&amp; cwd=${BASH_REMATCH[1]}
}

PROMPT_COMMAND=cwd

PS1="\$cwd \$"


I'd say not to count the tilde as a path component: it's only one extra character that carries a lot of information, well worth the single column.   The regex is then:

  [[ $cwd =~ (..|[^~])/([^/]+/[^/]+)$ ]] &amp;&amp; cwd=${BASH_REMATCH[2]}