导航到 ZSH (bash) 中的目录

JDi*_*522 3 shell zsh oh-my-zsh

我正在使用Oh-My-ZSH创建一些 ailises 和功能,以减轻我的重复工作负载。

我需要从我电脑的任何地方导航到我的前端目录。这就是我所拥有的:

frontend(){
  cd ~/Desktop/Work/Frontend
  cd $1
}
Run Code Online (Sandbox Code Playgroud)

现在,当我输入frontend或 时frontend myProject,这很有效,但是,我所有的项目文件夹都以类似的内容作为后缀.m.tablet等等。

我怎样才能写出以下内容:

  • 会让我自动导航到一个文件夹,然后是 .something

  • 当有多个选项(如project.mproject.tablet)时,将提示我类似的选项,如果您在终端中点击 Tab 并获得多个自动完成选项。

我希望我的问题是有道理的。

谢谢。

mkl*_*nt0 5

首先找到zsh解决方案,然后是bash解决方案。

更新:事实证明,zsh实现(基于 builtin compctl)比bash实现(基于 builtin complete)简单得多。

感兴趣的代码保存到一个文件(例如,frontend)和它(例如,. ./frontend); 以交互方式或最好从您的 bash/zsh 配置文件中获取。

一旦到位,子目录名称的自动完成~/Desktop/Work/Frontend将按如下方式工作:

  • 例如,键入,frontend myProject然后按 TAB。
  • myProject然后与 中的子目录的名称进行前缀匹配~/Desktop/Work/Frontend
    • 如果只有一场比赛, myProject将立即扩展到完整的子目录名称。
    • 否则,会发出蜂鸣声,表示有多个匹配项:
      • zsh: 所有匹配子目录的名称都会立即列出。
      • bash:再次按 T​​AB可列出所有匹配子目录的名称
      • 继续键入,直到前缀匹配明确为止,然后再次按 TAB。

注意:在 中bash,也只需按一次TAB 键即可列出多个匹配项,请将以下内容添加到您的 shell 配置文件中bind "set show-all-if-ambiguous on"


zsh解决方案:

# Define the shell function.
frontend(){
  cd ~/Desktop/Work/Frontend/"${1:-}"
}

# Tell zsh to autocomplete directory names in the same directory as
# the function's when typing a command based on the shell function.
compctl -/ -W ~/Desktop/Work/Frontend frontend
Run Code Online (Sandbox Code Playgroud)

bash解决方案:

注意:complete -o dirnames不幸的是,它不带参数 - 它总是自动完成当前目录。因此,需要一个返回潜在匹配项的自定义 shell 函数,结合-o filenames, 是必需的。

# Define the main shell function.
frontend(){
    local BASEDIR=~/Desktop/Work/Frontend
  cd "$BASEDIR/${1:-}"
}

# Define the custom completion function.
_frontend_completions() {
    local BASEDIR=~/Desktop/Work/Frontend

    # Initialize the array variable through which
    # completions must be passed out.
  COMPREPLY=() 

    # Find all matching directories in the base folder that start
    # with the name prefix typed so far and return them.
  for f in "$BASEDIR/${COMP_WORDS[COMP_CWORD]}"*; do
    [[ -d $f ]] && COMPREPLY+=( "$(basename "$f")" )
  done

}

# Tell bash to autocomplete directory names as returned by the
# _frontend_completions() helper functoin when typing a command 
# based on the main shell function.
complete -o filenames -F _frontend_completions frontend fe
Run Code Online (Sandbox Code Playgroud)