Bash完成时没有空格分隔的单词

时间:2011-07-22 08:44:34

标签: bash bash-completion

我正在完成一个命令,它接受像“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]将为“1”。

我可以很容易地从COMP_LINE解析命令行,但更好的方法是在我的自定义完成中找到一种方式让':'表现得像''。可能的?

2 个答案:

答案 0 :(得分:0)

首先采用自定义解析的解决方案。很想知道是否有更好的方法:

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

答案 1 :(得分:0)

不幸的是,并非如此。这实际上是bash的“功能”。

虽然您可以修改COMP_WORDBREAKS,但修改COMP_WORDBREAKS可能会引起其他问题,因为它是全局变量,并且会影响其他完成脚本的行为。

如果您看看the source for bash-completion,存在两种可以帮助解决此问题的辅助方法:

    带有-n选项的
  • _get_comp_words_by_ref可以使单词完整,而无需将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