在逐个命令的基础上为bash完成设置不区分大小写

Tan*_*lus 7 bash case-insensitive tab-completion

有没有办法指定特定命令具有不区分大小写,而不是全局打开不区分大小写(至少对于那个shell)?

在我的特定情况下,我有一个小应用程序,它让我命令行访问电子邮件地址的数据库,所以我输入:

db get email john smith
Run Code Online (Sandbox Code Playgroud)

然后它返回John Smith的电子邮件地址.所以我设法在应用程序内部完成启用:设置

COMPREPLY=($(compgen -W "$(db --complete $COMP_CWORD "$COMP_WORDS[@]"}")" -- ${COMP_WORDS[COMP_CWORD]}))
Run Code Online (Sandbox Code Playgroud)

可以让我选项卡完成getemail.但是,如果我输入j<tab>,它就会拒绝,因为在电子邮件数据库中,它是正确的大写.无论如何,我想得到bash来完成这个.(如果我使用资本J,它会起作用.)

如果不这样做,我可以让我的--complete选项通过匹配输入来改变其回复的情况,我想,但理想情况下,如果可能的话,命令行将匹配数据库.

请注意,我在使用readline时在app中工作,它只与bash接口,这似乎是一个问题.

mkl*_*nt0 6

实际上似乎没有办法compgen对单词list(-W)进行不区分大小写的匹配.我看到以下解决方法:

简单的解决方案:首先将单词列表和输入标记翻译为全小写.注意:如果所有完成都变为全小写,则这只是一个选项.

complete_lower() {

    local token=${COMP_WORDS[$COMP_CWORD]}
    local words=$( db --complete $COMP_CWORD "${COMP_WORDS[@]}" )

    # Translate both the word list and the token to all-lowercase.
    local wordsLower=$( printf %s "$words" | tr [:upper:] [:lower:] )
    local tokenLower=$( printf %s "$token" | tr [:upper:] [:lower:] )

    COMPREPLY=($(compgen -W "$wordsLower" -- "$tokenLower"))   
}
Run Code Online (Sandbox Code Playgroud)

更好,但更精细的解决方案:滚动自己的,不区分大小写的匹配逻辑:

complete_custommatch() {

    local token=${COMP_WORDS[$COMP_CWORD]}
    local words=$( db --complete $COMP_CWORD "${COMP_WORDS[@]}" )

    # Turn case-insensitive matching temporarily on, if necessary.
    local nocasematchWasOff=0
    shopt nocasematch >/dev/null || nocasematchWasOff=1
    (( nocasematchWasOff )) && shopt -s nocasematch

    # Loop over words in list and search for case-insensitive prefix match.
    local w matches=()
    for w in $words; do
        if [[ "$w" == "$token"* ]]; then matches+=("$w"); fi
    done

    # Restore state of 'nocasematch' option, if necessary.
    (( nocasematchWasOff )) && shopt -u nocasematch

    COMPREPLY=("${matches[@]}")
}
Run Code Online (Sandbox Code Playgroud)

  • 真正.引用是为了抨击安全套是什么性的...当你知道你可以在不使用它们的情况下离开时会更加激动......当你出错时,你并不总是立刻知道它... (3认同)
  • 如果搞乱购物,你可以使用一点点魔法:"$ {w ,,}"和"$ {token ,,}".:) (2认同)