Bash自动补全非空格分隔单词

4

我正在完成一个带有参数“one:two:three”的命令。

简单来说,我希望':'像空格一样被默认处理。我是否遗漏了一些简单的方法?

我发现':'在COMP_WORDBREAKS中,但COMP_WORDBREAKS中的字符也被视为单词。

因此,如果命令行是:

cmd one:tw[TAB]

COMP_CWORD将是3,COMP_WORDS [COMP_CWORD-1]将是“:”。

为了比较,如果命令行是:

cmd one tw[TAB]

COMP_CWORD将是2,而COMP_WORDS [COMP_CWORD-1]将是'one'

更糟糕的是,如果在“:”分隔符后立即按[TAB]键,则它的行为大多类似于空格:

cmd one:[TAB]

现在COMP_CWORD的值为2,COMP_WORDS[COMP_CWORD-1]的值为'one'。

我可以轻松地从COMP_LINE中解析命令行,但最好找到一种方法,使得在我的自定义完成中“:”的作用就像空格一样。这可行吗?

2个回答

1
很遗憾,实际上不行。这实际上是Bash的一个“特性”。虽然你可以修改COMP_WORDBREAKS,但修改COMP_WORDBREAKS可能会导致其他问题,因为它是一个全局变量,会影响其他完成脚本的行为。如果你查看Bash补全的源代码,会发现存在两个帮助方法可解决此问题:_get_comp_words_by_ref选项-n通过引用获取要完成的单词,而不考虑EXCLUDE中的字符作为单词分隔符。
# Available VARNAMES:
#     cur         Return cur via $cur
#     prev        Return prev via $prev
#     words       Return words via $words
#     cword       Return cword via $cword
#
# Available OPTIONS:
#     -n EXCLUDE  Characters out of $COMP_WORDBREAKS which should NOT be
#                 considered word breaks. This is useful for things like scp
#                 where we want to return host:path and not only path, so we
#                 would pass the colon (:) as -n option in this case.
#     -c VARNAME  Return cur via $VARNAME
#     -p VARNAME  Return prev via $VARNAME
#     -w VARNAME  Return words via $VARNAME
#     -i VARNAME  Return cword via $VARNAME
#
  • __ltrim_colon_completions 从 COMPREPLY 中删除包含冒号前缀的项目。
# word-to-complete.
# With a colon in COMP_WORDBREAKS, words containing
# colons are always completed as entire words if the word to complete contains
# a colon.  This function fixes this, by removing the colon-containing-prefix
# from COMPREPLY items.
# The preferred solution is to remove the colon (:) from COMP_WORDBREAKS in
# your .bashrc:
#
#    # Remove colon (:) from list of word completion separators
#    COMP_WORDBREAKS=${COMP_WORDBREAKS//:}
#
# See also: Bash FAQ - E13) Why does filename completion misbehave if a colon
# appears in the filename? - http://tiswww.case.edu/php/chet/bash/FAQ
# @param $1 current word to complete (cur)
# @modifies global array $COMPREPLY

例如:

例如:

{
    local cur
    _get_comp_words_by_ref -n : cur
    __ltrim_colon_completions "$cur"
}
complete -F _thing thing

0

首先尝试使用自定义解析方案。想知道是否有更好的方法:

parms=$(echo "$COMP_LINE" | cut -d ' ' -f 2)
vals="${parms}XYZZY"
IFS=$":"
words=( $vals )
unset IFS
count=${#words[@]}
cur="${words[$count-1]%%XYZZY}"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接