Different directory for bash_completion

◇◆丶佛笑我妖孽 提交于 2019-12-11 14:02:10

问题


To be able to enter dev my-[tab] anywhere on my system and receive auto completion like

$ dev my-[tab]
my-project
my-awesome-project

I created a file in /etc/bash_completion.d/ with the following content:

_dev()
{
    PROJECTS=$(ls /development)
    local cur=${COMP_WORDS[COMP_CWORD]}

    COMPREPLY=( $(compgen -W "${PROJECTS}" -- $cur) )
}

complete -F _dev dev

This works just fine, but I would also like to be able to auto-complete subfolders:

[~] $ dev my-p[tab]
[~] $ dev my-project/[tab][tab]
src    doc
[~] $ dev my-project/s[tab][enter]
[/development/my-project/src] $

So basically, I would like to have auto-completion for dev the same way it is for cd.

dev is only an alias:

alias dev='gotodev'
gotodev ()
{ 
    cd /development/$1
}

回答1:


Just wrote an example:

[/tmp] # cat compspec
g_proj_dir=/tmp/projects

dev()
{
    cd $g_proj_dir/$1
}

_dev()
{
    local cmd=$1 cur=$2 pre=$3
    local _cur compreply

    _cur=$g_proj_dir/$cur
    compreply=( $( compgen -d "$_cur" ) )
    COMPREPLY=( ${compreply[@]#$g_proj_dir/} )
    if [[ ${#COMPREPLY[@]} -eq 1 ]]; then
        COMPREPLY[0]=${COMPREPLY[0]}/
    fi
}

complete -F _dev -o nospace dev
[/tmp] # source ./compspec
[/tmp] #
[/tmp] # cd /tmp/
[/tmp] # mkdir -p projects/{bar,foo}{1,2}/mod{1,2}/submod{1,2}
[/tmp] # touch    projects/{bar,foo}{1,2}/mod{1,2}/submod{1,2}/file{1,2}
[/tmp] # dev <TAB><TAB>
bar1  bar2  foo1  foo2
[/tmp] # dev f<TAB>
[/tmp] # dev foo
[/tmp] # dev foo<TAB><TAB>
foo1  foo2
[/tmp] # dev foo2<TAB>
[/tmp] # dev foo2/
[/tmp] # dev foo2/<TAB>
[/tmp] # dev foo2/mod
[/tmp] # dev foo2/mod<TAB><TAB>
foo2/mod1  foo2/mod2
[/tmp] # dev foo2/mod2<TAB>
[/tmp] # dev foo2/mod2/
... ...


来源:https://stackoverflow.com/questions/38737675/different-directory-for-bash-completion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!