How to specify a custom autocomplete for specific commands?

The easiest way of doing this is to include a shell script in /etc/bash_completion.d/. The basic structure of this file is a simple function that performs the completion and then invocation of complete which is a bash builtin. Rather than go into detail on how to use complete, I suggest you read An Introduction to Bash Completion. Part 1 covers the basics and Part 2 gets into how you would go about writing a completion script.

A denser description of bash completion can be found in the "Programmable Completion" section of man bash (you can type "/Programmable Completion" and then press 'n' a few times to get there quickly. Or, if you are feeling luck, "g 2140 RETURN").


Here is basic guide.

Lets have an example of script called admin.sh to which you would like to have autocomplete working.

#!/bin/bash

while [ $# -gt 0 ]; do
  arg=$1
  case $arg in
    option_1)
     # do_option_1
    ;;
    option_2)
     # do_option_1
    ;;
    shortlist)
      echo option_1 option_2 shortlist
    ;;
    *)
     echo Wrong option
    ;;
  esac
  shift
done

Note option shortlist. Calling script with this option will print out all possible options for this script.

And here you have the autocomplete script:

_script()
{
  _script_commands=$(/path/to/your/script.sh shortlist)

  local cur prev
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  COMPREPLY=( $(compgen -W "${_script_commands}" -- ${cur}) )

  return 0
}
complete -o nospace -F _script ./admin.sh

Note that the last argument to complete is the name of the script you want to add autocompletion to. All you need to do is to add your autocomplete script to bashrc as

source /path/to/your/autocomplete.sh

or copy it to /etc/bash.completion.d

Source: https://askubuntu.com/a/483149/24155