bash选项卡补全(带空格) [英] bash tab completion with spaces

查看:73
本文介绍了bash选项卡补全(带空格)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当可能的选项可能包含空格时,我在bash补全方面遇到了问题.

I'm having a problem with bash-completion when the possible options may contain spaces.

比方说,我想要一个回显第一个参数的函数:

Let's say I want a function which echoes the first argument:

function test1() {
        echo $1
}

我生成了一个可能的完成选项列表(有些有空格,有些没有空格),但是我无法正确处理空格.

I generate a list of possible completion options (some have spaces, some not), but I don't manage to handle spaces correctly.

function pink() {
    # my real-world example generates a similar string using awk and other commands
    echo "nick\ mason syd-barrett david_gilmour roger\ waters richard\ wright"
}

function _test() {
    cur=${COMP_WORDS[COMP_CWORD]}
    use=`pink`
    COMPREPLY=( $( compgen -W "$use" -- $cur ) )
}
complete -o filenames -F _test test

尝试此操作时,我得到:

When I try this, I get:

$ test <tab><tab>
david_gilmour  nick           roger          waters
mason          richard        syd-barrett    wright
$ test r<tab><tab>
richard  roger    waters   wright

这显然不是我的意思.

如果我没有为 COMPREPLY 分配一个数组,即仅 $(compgen -W"$ use"-$ cur),如果仅剩一个选择:

If I don't assign an array to COMPREPLY, i.e. only $( compgen -W "$use" -- $cur ), I get it working if only one option remains:

$ test n<tab>
$ test nick\ mason <cursor>

但是,如果还有几个选项,它们都将用单引号引起来:

But if several options remain, they are all printed within single quotes:

$ test r<tab><tab>
$ test 'roger waters
richard wright' <cursor>

我的 COMPREPLY 变量一定有问题,但是我不知道是什么...

There must be something wrong with my COMPREPLY variable, but I can't figure out what...

(在solaris上运行bash,以防造成影响...)

(running bash on solaris, in case that makes a difference...)

推荐答案

如果您需要处理字符串中的数据,则可以使用Bash内置的字符串替换运算符.

If you need to process the data from the string you can use Bash's built-in string replacement operator.

function _test() {
    local iter use cur
    cur=${COMP_WORDS[COMP_CWORD]}
    use="nick\ mason syd-barrett david_gilmour roger\ waters richard\ wright"
    # swap out escaped spaces temporarily
    use="${use//\\ /___}"
    # split on all spaces
    for iter in $use; do
        # only reply with completions
        if [[ $iter =~ ^$cur ]]; then
            # swap back our escaped spaces
            COMPREPLY+=( "${iter//___/ }" )
        fi
    done
}

这篇关于bash选项卡补全(带空格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆