什么是ZSH中的%〜(代字号百分比)?

use*_*166 6 macos shell zsh

我正在尝试自定义这个 oh-my-zsh主题.

我在其中找到了这段代码,显然打印了dir名称(如果我错了,请纠正我).

# Dir: current working directory
prompt_dir() {
  prompt_segment blue black '%~'
}
Run Code Online (Sandbox Code Playgroud)

和prompt_segment定义为

# Begin a segment
# Takes two arguments, background and foreground. Both can be omitted,
# rendering default background/foreground.
prompt_segment() {
  local bg fg
  [[ -n $1 ]] && bg="%K{$1}" || bg="%k"
  [[ -n $2 ]] && fg="%F{$2}" || fg="%f"
  if [[ $CURRENT_BG != 'NONE' && $1 != $CURRENT_BG ]]; then
    echo -n " %{$bg%F{$CURRENT_BG}%}$SEGMENT_SEPARATOR%{$fg%} "
  else
    echo -n "%{$bg%}%{$fg%} "
  fi
  CURRENT_BG=$1
  [[ -n $3 ]] && echo -n $3
}
Run Code Online (Sandbox Code Playgroud)

这个输出并不总是只是目录路径.如果我在一个也存在于ENV变量中的路径中,它将用该变量替换路径.

如果我在

/Users/abc/.oh-my-zsh/custom
Run Code Online (Sandbox Code Playgroud)

并且$ ZSH_CUSTOM是

/Users/abc/.oh-my-zsh/custom
Run Code Online (Sandbox Code Playgroud)

我刚进入$ZSH_CUSTOM命令提示符.

所以我的问题是,1)%~发送的是什么prompt_dir,2)这段编码从哪里得到当前工作目录,以及3)如何使它始终输出真实路径.

ZyX*_*ZyX 11

参见以下EXPANSION OF PROMPT SEQUENCES部分man zshmisc:

   %d
   /      Current  working  directory.   If an integer follows the `%', it
          specifies a number of trailing components of the current working
          directory  to show; zero means the whole path.  A negative inte?
          ger specifies leading components, i.e. %-1d specifies the  first
          component.

   %~     As  %d  and %/, but if the current working directory has a named
          directory as its prefix, that part is replaced by a `~' followed
          by  the  name  of  the directory.  If it starts with $HOME, that
          part is replaced by a `~'.
Run Code Online (Sandbox Code Playgroud)

  • @user1527166 这不就是 `%~` 的作用吗?大多数时候,您不会遇到“命名目录作为前缀”的情况,除非您经常通过命名目录散列或特殊函数(不记得其名称)来使用它们。 (2认同)