Customize tab completion in shell

放肆的年华 提交于 2019-12-03 10:29:10

You will likely find a file on your system called /etc/bash_completion which is full of functions and complete commands that set up this behavior. The file will be sourced by one of your shell startup files such as ~/.bashrc.

There may also be a directory called /etc/bash_completion.d which contains individual files with more completion functions. These files are sourced by /etc/bash_completion.

This is what the wine completion command looks like from the /etc/bash_completion on my system:

complete -f -X '!*.@(exe|EXE|com|COM|scr|SCR|exe.so)' wine

This set of files is in large part maintained by the Bash Completion Project.

You can take a look at Programmable Completion in bash manual to understand how it works.

I know this is old but I was looking to do something similar with a script of my own.

You can play around with an example I made here: http://runnable.com/Uug-FAUPXc4hAADF/autocomplete-for-bash

Pasted code from above:

# Create function that will run when a certain phrase is typed in terminal
# and tab key is pressed twice
_math_complete()
{
    # fill local variable with a list of completions
    local COMPLETES="add sub mult div"
    # you can fill this variable however you want. example:
    # ./genMathArgs.sh > ./mathArgsList
    # local COMPLETES=`cat ./mathArgsList`

    # we put the completions into $COMPREPLY using compgen
    COMPREPLY=( $(compgen -W "$COMPLETES" -- ${COMP_WORDS[COMP_CWORD]}) )
    return 0
}

# get completions for command 'math' from function '_math_complete()'
complete -F _math_complete math 

# print instructions
echo ""
echo "To test auto complete do the following:"
echo "Type math then press tab twice." 
echo "You will see the list we created in COMPLETES"
echo ""
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!