【问题标题】:What is %~ (percent tilde) in ZSH?ZSH 中的 %~ (百分号)是什么?
【发布时间】:2012-11-19 14:00:51
【问题描述】:

我正在尝试自定义this oh-my-zsh 主题。

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

# Dir: current working directory
prompt_dir() {
  prompt_segment blue black '%~'
}

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
}

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

如果我在

/Users/abc/.oh-my-zsh/custom

$ZSH_CUSTOM 是

/Users/abc/.oh-my-zsh/custom

我只是在命令提示符下得到$ZSH_CUSTOM

所以我的问题是,1) 从prompt_dir 发送的%~ 是什么,2) 这段代码从哪里获取当前工作目录,以及 3) 我怎样才能使它总是 输出真实路径。

【问题讨论】:

  • 感谢您提出这个问题。我还试图编辑 agnoster 主题,因为目录提示变得很大。将 '%~' 更改为 '%2d' 效果很好。

标签: macos shell zsh


【解决方案1】:

参见man zshmiscEXPANSION OF PROMPT SEQUENCES 部分:

   %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 `~'.

【讨论】:

  • 优秀:)。还有一个愿望 - 我可以用~ 替换我的主目录并同时使用%d 吗?我想要完整路径,减去 $HOME~ 替换。
  • @user1527166 这不正是%~ 所做的吗?大多数情况下,您不会遇到“命名目录作为其前缀”的情况,除非您经常通过命名目录哈希或特殊函数(不记得它的名称)使用它们。
  • 使用${PWD/~/\~}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多