Add bash autocompletion for your own script

Let your script be named utstart, and accepts any of the following arguments: start, stop, install, uninstall.

As an example, you would perhaps run your script like this from bash:

./utstart start

You would like to autocomplete start, by pressing TAB key like this:

./utstart s[TAB]

This is easy.

Prerequisite:

Install bash-completion package.

apt-get install bash-completion

Now create a new script like this:

#!/bin/bash
_utstart()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="start stop install uninstall"

    if [[ ${cur} == * && ${COMP_CWORD} -eq 1 ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}
complete -F _utstart -o filenames utstart

Note that we have added the options “start stop install uninstall” in the script. Note also the last line contains the name of the function in our auto completion script, and also the name of our main bash script, which accepts autocompletion entries.

Once done, copy this file to /etc/bash_completion.d/utstart-auto.

Now you may change permissions on it to make it executable.

chmod +x /etc/bash_completion.d/utstart-auto

Source it with:

. /etc/bash_completion.d/utstart-auto

Now try the following:

./utstart s[TAB}

 

You will now be presented with start and stop as options.