3

I am experimenting with moving from bash to zsh, and in particular with the hash function; so that

hash -d Do=~/Downloads

means I can enter cd Do to move immediately to that directory. Nice. But in the prompt, the directory is given as ~Do instead of ~/Downloads which is what I'd prefer to see. Is there any way of using directory hash values so that the prompt expands to the full directory name (with an initial ~ if in the user directory)?

1

The prompt escape %~ abbreviates the current directory using hashed directories whenever possible. To stop using directory abbreviations, you can use %/ instead, but that doesn't abbreviate the home directory either.

To abbreviate the home directory only, set the prompt_subst option (this may require adding additional backslashes in places in your prompt). Instead of %~ or %/, use a manual expansion from $PWD.

setopt prompt_subst
PS1='%B${${PWD/#%$HOME%/\~\/}/#$HOME/\~}\$%b '

If you want to perform more complex substitutions, you can set a variable in the chpwd hook and use it in your prompt. Even for the simple case shown above, this approach is more verbose but arguably more readable.

setopt prompt_subst
chpwd () {
  case $PWD in
    $HOME/*) prompt_PWD=\~/${PWD#$HOME};;
    $HOME) prompt_PWD=\~;;
    *) prompt_PWD=$PWD;;
  esac
}
PS1='%B$prompt_PWD\$%b '

You may prefer a hybrid approach that expands only certain hashed directories. This is easy to plug into the chpwd approach (or even into the direct approach, but it's less readable). For example, the following chpwd command abbreviates only directories that start with /home (presumably other users' home directories) and that aren't under your home directory.

chpwd () {
  case $PWD in
    $HOME/*) prompt_PWD=\~/${PWD#$HOME};;
    $HOME) prompt_PWD=\~;;
    /home/*) prompt_PWD=${(%)${:-%~}};;
    *) prompt_PWD=$PWD;;
  esac
}
0

Adding a trailing / to the directory name would achieve the desired effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.