为第一个参数配置自动完成,别管其他的

Dom*_*ger 3 bash autocomplete

我有一个需要大量不同参数的实用程序。现在,我想自动完成第一个参数,但让所有其他参数落入正常的自动完成。我怎么做?

function _my_autocomplete_()
{
    case $COMP_CWORD in
        1) COMPREPLY=($(compgen -W "$(get_args_somehow)" -- ${COMP_WORDS[COMP_CWORD]}));;
        *) # What goes here?
    esac
}

complete -F _my_autocomplete_ mycommand
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 5

显然我完全错过了你的问题。答案是没有明确定义的“正常自动完成”。但是,如果您知道您希望它完成什么样的事情(文件、别名、pid、变量名称等),您可以为compgen. 请参阅此 compgen 手册页,特别是-A下面的选项complete(它们是相同的)。例如,如果你想完成文件名,你可以使用这个:

compgen -f -- "${COMP_WORDS[COMP_CWORD]}"
Run Code Online (Sandbox Code Playgroud)

如果要完成命令(包括别名、函数等),可以使用以下命令:

compgen -back -A function -- "${COMP_WORDS[COMP_CWORD]}"
Run Code Online (Sandbox Code Playgroud)

使用$COMP_CWORD来获得正在完成这个词的索引。如果索引不是 1,则设置$COMPREPLY()并返回。

COMP_CWORD

    An index into ${COMP_WORDS} of the word containing the current 
    cursor position. This variable is available only in shell functions
    invoked by the programmable completion facilities
Run Code Online (Sandbox Code Playgroud)

  • @DominicRodger 在 `complete -F _my_autocomplete_ mycommand` 命令中,添加 `-o filenames`。 (2认同)