仅显示bash自动完成建议的基本名称

时间:2019-12-23 21:29:02

标签: bash path autocomplete

我有一个脚本(我们将其称为script),该脚本带有一个参数,该参数应该是具有特定扩展名的文件的路径,例如.txt。我希望能够自动完成其他目录中.txt文件的路径,并且希望它的行为类似于cd命令自动完成长路径的方式。

例如,在这样的文件夹结构中:

.
├── dir1
│   ├── a.txt
│   └── extra
├── dir2
│   ├── b.txt
│   ├── dir3
│   │   ├── c.txt
│   │   └── extra
│   └── extra
└── extra

$ script [tab][tab]应该产生:

dir1/ dir2/

以下是我无法弄清的一点:我想$ script dir2/ [tab][tab]提出建议:

dir3/ b.txt

而不是

dir2/dir3 dir2/b.txt

但是,如果我用不包含目录前缀的值填充COMPREPLY,并且在只有1个补全的情况下打了Tab键,则整个参数都将替换为建议。

例如,script dir2/b[tab]应该完成script b.txt时才完成script dir2/b.txt


这是我到目前为止(/etc/bash_completion.d/script)所完成的脚本:

_script()
{
    local cur
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"

    # Start with all of the directories
    _filedir -d

    # Get the basename of what's been typed so far ("b" for "a/b", "" for "a/")
    basename="$(basename "$cur." | sed 's/\.$//')"

    # Get the dirname of what's been typed so far ("a/b" for "a/b/c" and for "a/b/")
    dirname="$(dirname "$cur.")"

    # Get every .txt file in $dirname whose name starts with $basename

    # Version 1: completes correctly, but the list of suggestions includes the full path:
    TXTs=( $(cd "$dirname" && compgen -o filenames -f -X '!*.txt' -- "$basename" | sed 's/$/ /' | sed 's#^#'"$dirname/"'#' ) )

    # Version 2: Succinct (like cd), but does not complete correctly.
    TXTs=( $(cd "$dirname" && compgen -o filenames -f -X '!*.txt' -- "$basename" | sed 's/$/ /' ) )

    # Add the .txt files to the completion options list
    COMPREPLY+=( "${TXTs[@]}" )
}

complete -F _script script

如何在不中断制表符完成的情况下缩写建议列表中的路径?

0 个答案:

没有答案
相关问题