Bash completion from another completion

泄露秘密 提交于 2019-12-07 16:21:22

问题


I have a script that requires as an argument the name of command and arguments of that command.

So I want to write a completion function that would complete the name of the command and would complete the arguments for that command.

So I can complete the name of the command like this

if [[ "$COMP_CWORD" == 1 ]]; then
    COMPREPLY=( $( compgen -c ${COMP_WORDS[COMP_CWORD]} ))
else
    #Don't know what to write here
fi

So this will complete the first argument to list of shell commands that are available to run. And on second and other arguments I need a completion for ${COMP_WORDS[COMP_CWORD]} command.

I thought about removing first element from COMP_WORDS, decreasing COMP_CWORD by one and call a function _${COMP_WORDS[0]} with name that prefixes "_" to the command, because in many examples the function that completes a command has such name, but when I executed complete -p in bash I found that many commands are completed with functions that has different names. And as for me, such solution looks really bad.

I'm not a bash scripting guru so I just don't know where to start searching the solution.


回答1:


Your requirement is similar to the command completion for exec or time or xargs. These commands also take a command & that command's arguments as completion options.

Checking the bash_completion option for exec:

$ complete -p exec
complete -F _command exec

You can re-use the same function _command as your completion function..

Usage:

complete -F _command your-script.sh


来源:https://stackoverflow.com/questions/29231639/bash-completion-from-another-completion

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