Shorten path in zsh prompt

To get a similar effect like in bash, that is including the ..., try:

%(4~|.../%3~|%~)

This checks, if the path is at least 4 elements long (%(4~|true|false)) and, if true, prints some dots with the last 3 elements (.../%3~), otherwise the full path is printed %~.


I noticed that bash seems to shorten paths in the home directory differently, for example:

~/.../some/long/path

For a similar effect, you may want to use:

%(5~|%-1~/…/%3~|%4~)

This checks, whether the path is longer then 5 elements, and in that case prints the first element (%-1~), some dots (/…/) and the last 3 elements. It is not exactly the same as paths, that are not in your home directory, will also have the first element at the beginning, while bash just prints dots in that case. So

/this/…/some/silly/path

instead of

.../some/silly/path

But this might not necessarily a bad thing.


In addition to the other answers given here, you can also use %< to truncate the path to a given number of characters. I find this preferable to using %<n>d, since individual path elements may obviously be quite long in themselves. Using %< yields a far more predictable maximum prompt length.

For example, to left-truncate the path element with tilde expansion (%~) to 15 characters, replacing removed characters with .., you can do something like this:

PROMPT='%n@%m:%15<..<%~%<<%# '

This is documented in the Zsh manual under Prompt Expansion, right at the end of the page.


You can use %3d prompt expansion:

/home/cuonglm/.config/fish/functions $ PS1='%3d $ '
.config/fish/functions $

The general form is %d, if any positive integer follow d specifies the trailing components to show of current path, zero mean show the whole path, negative integer means the leading path to show:

.config/fish/functions $ PS1='%-2d $ '
/home/cuonglm $

Tags:

Prompt

Zsh