zsh - 以独特的方式折叠zsh提示中的目录

标签 zsh prompt pwd

有没有办法以独特的方式在zsh提示符下折叠当前工作目录,以便我可以将其复制并粘贴到另一个终端,点击TAB并获取原始路径?

假设我们有以下目录:

/adam/devl
/alice/devl
/alice/docs
/bob/docs

如果提示被编程为显示前几个字符,并且我在/b/d中,则它是唯一的。另一方面,/a/d不是唯一的,因此我需要/ad/d,/al/de和/al/do。甚至在用户alex出现时,甚至是/ali/…。

是否可以直接在zsh中破解它,还是我需要编写一个脚本来查找每个父目录的最短唯一开头?

谢谢您的想法!

最佳答案

我不知道zsh具有这种内置功能,但是无需借助单个subshel​​l或慢速管道就可以很容易地编写脚本:

#!/bin/zsh

paths=(${(s:/:)PWD})

cur_path='/'
cur_short_path='/'
for directory in ${paths[@]}
do
  cur_dir=''
  for (( i=0; i<${#directory}; i++ )); do
    cur_dir+="${directory:$i:1}"
    matching=("$cur_path"/"$cur_dir"*/)
    if [[ ${#matching[@]} -eq 1 ]]; then
      break
    fi
  done
  cur_short_path+="$cur_dir/"
  cur_path+="$directory/"
done

printf %q "${cur_short_path: : -1}"
echo

该脚本将输出自动完成工作所需的最短路径。

您可以将其作为函数放入.zshrc中,然后从任何目录运行它。

function spwd {
  paths=(${(s:/:)PWD})

  cur_path='/'
  cur_short_path='/'
  for directory in ${paths[@]}
  do
    cur_dir=''
    for (( i=0; i<${#directory}; i++ )); do
      cur_dir+="${directory:$i:1}"
      matching=("$cur_path"/"$cur_dir"*/)
      if [[ ${#matching[@]} -eq 1 ]]; then
        break
      fi
    done
    cur_short_path+="$cur_dir/"
    cur_path+="$directory/"
  done

  printf %q "${cur_short_path: : -1}"
  echo
}

这是一个正在运行的视频:

https://asciinema.org/a/0TyL8foqvQ8ec5ZHS3c1mn5LH

或者,如果您愿意,可以提供一些示例输出:

~/t $ ls
adam  alice  bob  getshortcwd.zsh

~/t $ ls adam
devl

~/t $ ls alice
devl  docs

~/t $ spwd
/h/v/t

~/t $ cd adam/devl

~/t/adam/devl $ spwd
/h/v/t/ad/d

~/t/adam/devl $ cd ../../alice/devl

~/t/alice/devl $ spwd
/h/v/t/al/de

~/t/alice/devl $ cd ../docs

~/t/alice/docs $ spwd
/h/v/t/al/do

~/t/alice/docs $ `spwd` [TAB]
~/t/alice/docs $ /h/v/t/al/do [TAB]
~/t/alice/docs $ /home/vsimonian/t/alice/docs

关于zsh - 以独特的方式折叠zsh提示中的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45263799/

相关文章:

alias - 使用带颜色/格式字符的 echo 时出现 Zsh 问题

user-interface - Powershell host.ui.prompt 从命令行运行时不弹出对话框

vim - zsh 函数退出后搞砸了提示

makefile - 重击 : What is the difference between PWD and CURDIR?

c - 如何使用 C 函数执行 Shell 内置命令?

bash - 重命名文件但将它们保留在当前的子目录中

git - 如何在终端中显示 git 用户 (oh-my-zsh)

macos - OSX中的zsh编译问题

zsh 无法将历史保存到 .zhistory

twitter-bootstrap-3 - 引导模式中的 SweetAlert 提示问题