How can I shortern my command line prompt’s current directory?

For people looking for a much simpler solution and don’t need the name of the first directory in the path, Bash has built-in support for this using the PROMPT_DIRTRIM variable. From the documentation:

PROMPT_DIRTRIM

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Printing a Prompt). Characters removed are replaced with an ellipsis.

For example:

~$ mkdir -p a/b/c/d/e/f
~$ cd a/b/c/d/e/f
~/a/b/c/d/e/f$ export PROMPT_DIRTRIM=2
~/.../e/f$ PROMPT_DIRTRIM=3
~/.../d/e/f$ 

Downside: It depends on the directory level, not the length of the path, which you might not want.

Upside: It’s very simple. Just add export PROMPT_DIRTRIM=2 to your .bashrc.

Leave a Comment