How do I get bash completion for command aliases?

Try complete-alias, which solves this problem exactly. (Disclaimer: I am the author of complete_alias)

After install it you can use one generic function to complete many aliases like this:

complete -F _complete_alias <myalias1>
complete -F _complete_alias <myalias2>
complete -F _complete_alias <myalias3>

You may want to source the complete_alias file in every bash instance through .bash_profile or similar.

installation

mkdir ~/.bash_completion.d
curl https://raw.githubusercontent.com/cykerway/complete-alias/master/complete_alias \
     > ~/.bash_completion.d/complete_alias

application

source ~/.bash_completion.d/complete_alias

alias container=docker\ container
complete -F _complete_alias container

container can now be autocompleted by the original _docker() completion handler;

$ container l<Tab>
logs  ls    

$ container s<Tab>
start  stats  stop   

There is a great thread about this on the Ubuntu forums. Ole J proposes the following alias completion definition function:

function make-completion-wrapper () {
  local function_name="$2"
  local arg_count=$(($#-3))
  local comp_function_name="$1"
  shift 2
  local function="
    function $function_name {
      ((COMP_CWORD+=$arg_count))
      COMP_WORDS=( "$@" \${COMP_WORDS[@]:1} )
      "$comp_function_name"
      return 0
    }"
  eval "$function"
  echo $function_name
  echo "$function"
}

Use it to define a completion function for your alias, then specify that function as a completer for the alias:

make-completion-wrapper _apt_get _apt_get_install apt-get install
complete -F _apt_get_install apt-inst

I prefer to use aliases for adding always-used arguments to existing programs. For instance, with grep, I always want to skip devices and binary files, so I make an alias for grep. For adding new commands such as grepbin, I use a shell script in my ~/bin folder. If that folder is in your path, it will get autocompleted.


By googling this issue I ended up here, so I tried the approaches in the other answers. For various reasons I don't actually understand, they never behaved properly in my Ubuntu 16.04.

What in the end worked for me was way more trivial than expected. I wanted to use the same autocompletion as rsync has for mycommand. Hence, I looked up the autocompletion function, and then called complete accordingly.

# Lookup of name of autocompletion function used for rsync
complete -p rsync
# Returns: complete -o nospace -F _rsync rsync

# Sourcing the rsync functions before, then using the same function for 'mycommand'
. /usr/share/bash-completion/completions/rsync
complete -o nospace -F _rsync mycommand

Disclaimer: I'm not sure what's the downside of my approach compared to the others. I mainly wrote this as it could help people where this trivial approach might be enough.