11.10. 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 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.

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

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 <mikhailian at altern dot org> who rewrote the code to utilize new Bash functionality, thus speeding it up considerably.

Risto Juola (risto AT risto.net) wrote to say that he preferred to have the "~" in the $newPWD, so he wrote another version:

Relative speed: the first version takes about 0.45 seconds on an unloaded 486SX25. Risto's version takes about 0.80 to 0.95 seconds. The variation in this case is due to whether or not truncation is required.