10.11. Controlling the Size and Appearance of $PWD

Unix allows long file names, which can lead to the value of $PWD being very long. Some people (notably the authors of the default RedHat prompt) choose to use the basename of the current working directory (ie. "giles" if $PWD="/home/giles"). I like more info than that, but it's often desirable to limit the length of the directory name, and it makes the most sense to truncate on the left.

function prompt_command {
# How many characters of the $PWD should be kept
local pwdmaxlen=30
# Indicator that there has been directory truncation:
local trunc_symbol="..."
if [ ${#PWD} -gt $pwdmaxlen ]
then
  local pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
  newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
else
  newPWD=${PWD}
fi
}
PROMPT_COMMAND=prompt_command

The above code can be executed as part of PROMPT_COMMAND, and the environment variable generated (newPWD) can then be included in the prompt. Thanks to Alexander Mikhailian who rewrote the code to utilize new Bash functionality, thus speeding it up considerably.

Here's another version that keeps "~" as an indication of being in your home directory:

function prompt_command {
pwd_len=20
newPWD=$(pwd)
newPWD=${newPWD/#${HOME}/\~} # Replace home dir with ~
if [ ${#newPWD} -gt ${pwd_len} ]
then
  if [ "${newPWD:0:1}" = "~" ]
  then
    newPWD="~..${newPWD:$((${#newPWD}-${pwd_len}))}"
  else
    newPWD="...${newPWD:$((${#newPWD}-${pwd_len}))}"
  fi
fi
}
PROMPT_COMMAND=prompt_command

"sqrt(2)/2" wrote in with an elegant solution for keeping track of the depth you are in the directory tree without having a long directory name:

echo $(pwd|sed 's-[^/]\+/-/-g')

With this, /usr/man/man1 becomes ///man1, and /usr/local/man/man1 becomes ////man1.

Relative speed: on an unloaded 800MHz Celeron, the first method takes negligible time. The second method (with "~" substitution) takes about 0.022-0.030 seconds. The last version (multiple slashes) takes about 0.043 seconds.