bash - 如何在其他目录中扩展 bash 补全?

标签 bash autocomplete bash-completion

我正在学习 bash 补全。我只能列出当前目录的内容。这是我的代码:

   _foo()
   {
       local cur prev opts
       COMPREPLY=()
       cur="${COMP_WORDS[COMP_CWORD]}"
       prev="${COMP_WORDS[COMP_CWORD-1]}"

       opts="push pull"
       OUTPUT=" $(ls) "

      case "${prev}" in
          push)
              COMPREPLY=( $(compgen -W "--in --out" -- ${cur}) )
              return 0
              ;;
          --in)
              COMPREPLY=( $(compgen -W "$OUTPUT" -- ${cur}) )
              return 0
              ;;
      esac

        COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
        return 0
  }
  complete -F _foo foo

它的输出是:

$ foo push --in[TAB]
file1.txt file2.txt foo  ;; content of pwd

但是当我这样做时:

$ foo push --in ~[TAB]

它不工作。 所以我想知道如何在不同的目录中完成 bash(不仅仅是在 pwd 中)?谢谢。

最佳答案

您可以使用-f来匹配文件名:

#!/bin/bash
_foo()    {
       local cur prev opts
       COMPREPLY=()
       cur="${COMP_WORDS[COMP_CWORD]}"
       prev="${COMP_WORDS[COMP_CWORD-1]}"
       opts="push pull"

       case "${prev}" in
          push)
              COMPREPLY=( $(compgen -W "--in --out" -- ${cur}) )
              return 0
              ;;
          --in)
              COMPREPLY=( $(compgen -f ${cur}) )
              return 0
              ;;
      esac

      COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
      return 0   
}

complete -F _foo foo

但是,它似乎不适用于单独的 ~$ foo push --in ~/[TAB] 以及所有其他目录 此解决方案不会包含斜杠来在目录中查找文件: $ foo push --in/etc[TAB] 将给出 foo push --in/etc 而不是 foo push --in/etc/

以下帖子使用默认模式解决了该问题:
Getting compgen to include slashes on directories when looking for files

default

Use Readline’s default filename completion if the compspec generates no matches.

所以你可以使用:

#!/bin/bash
_foo()
   {
       local cur prev opts
       COMPREPLY=()
       cur="${COMP_WORDS[COMP_CWORD]}"
       prev="${COMP_WORDS[COMP_CWORD-1]}"

       opts="push pull"
       OUTPUT=" $(ls) "

      case "${prev}" in
          push)
              COMPREPLY=( $(compgen -W "--in --out" -- ${cur}) )
              return 0
              ;;
          --in)
              COMPREPLY=()
              return 0
              ;;
          --port)
              COMPREPLY=("")
              return 0
              ;;
      esac

        COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
        return 0
  }
  complete -o default -F _foo foo

或者当您需要喜欢这篇文章时设置为默认模式:https://unix.stackexchange.com/a/149398/146783

关于bash - 如何在其他目录中扩展 bash 补全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38285872/

相关文章:

objective-c - Mac OS X 应用程序中的 Bash 脚本,从系统调用自定义应用程序

升级到 jQuery UI 1.10.3 后,jQuery 自动完成下拉列表不显示

bash - 在 Bash 脚本中调用 "read"时获取自动完成

bash - 在不打印作业和进程 ID 的情况下在后台运行 bash 命令

c - 使用 C 样式转义序列转义二进制文件

bash - 对交互式脚本使用 yes 会导致退出代码 141

linux - 将多个文件 append 到单个输出文件,但文件之间有消息

php - 数据库自动完成功能不起作用

jquery - Grails - jQuery UI 自动完成功能不起作用

bash - 带有 bash 大括号扩展的 cp 复制命令