Controlling the size of the $PWD in bash

I just fixed a 6-year old bug in the 5 lines of code that I use at least 100 times a day, every day, including weekends and holidays. Now, I can finally publish it.

function truncate_pwd
{
 if [ $HOME == $PWD ]
 then
   newPWD="~"
 elif [ $HOME ==  ${PWD:0:${#HOME}} ]
 then
   newPWD="~${PWD:${#HOME}}"
 else
   newPWD=$PWD
 fi

  local pwdmaxlen=15
  if [ ${#newPWD} -gt $pwdmaxlen ]
  then
    local pwdoffset=$(( ${#newPWD} - $pwdmaxlen  ))
    newPWD=".+${newPWD:$pwdoffset:$pwdmaxlen}"
  fi
}

PROMPT_COMMAND=truncate_pwd
PS1="${ttyname}@\[${HOST_COLOUR}\]\h\[${RESET_COLOR}\]:\${newPWD}\\$ "

Just put the above snippet of code into ~/.bashrc

Debian shows the absolute path in the command prompt by default, and it can be really long, sometimes.To fix this, we can limit the command prompt to show only the last x characters using only the variable expansion features of bash 2.0.5+. Since this code does not fork out sed, tr or wc, it is blazingly fast.