问题
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