Implement autocompletion in your own bash script

In the era when Linux and DOS coexisted in the 1990s, Linux Shells had one of the most trivial but most practical functions, which was command auto-completion. And the DOS idiot didn't learn what it means to be easy to use until he died.

This humble little tradition of Linux continues to this day. Although it seems insignificant, it actually greatly improves the administrator's input efficiency and accuracy.

 

If you need to implement the auto-completion function in your own script, you only need to write a script similar to the following, and source it every time the user logs in.

This example is on the company's channel machine. You can log in to the relevant server according to the name, but the server name is long and difficult to remember, and it is very troublesome to enter every time. So there is this autocompletion script:

 

tongdaoji() 
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="java.vm swift.sa openstack.zf shanghai venusweb database"

    if [[ ${cur} == * ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}

complete -F tongdaoji e


Put this script in a place where it can be executed automatically every time you log in, such as ~/.bashrc or /etc/bash_completion.d/. Then just type in

 

e o<TAB>

you can get

e openstack.zf

up.

Guess you like

Origin blog.csdn.net/ffb/article/details/9194711