See the repo for this script here.
I like efficiency and minimizing keystrokes.
For my EC2 management script, I needed to specify the host’s name like this:
ec2 start some_host_name
I didn’t really want to type out the host name every time, so I threw together an autocompletion script.
This way, I can type this:
ec2 start so<tab>
and have it autocomplete to this:
ec2 start some_host_name
I don’t do completions all the time, so a good guide is An Introduction to Bash Completion.
I started with my completion script that looks like this:
ec2_bash_completion:
# Adds tab-completion of SSH config Hosts to the ec2 command.
#
# Install by putting this line in your .bash_profile or .bashrc.
#
# . $HOME/path/to/ec2_bash_completion
#
# Then reload with `. ~/.bashrc`.
_ec2_hosts()
{
# Get a list of hostnames from ~/.ssh/config
local hosts=$(grep -E "^Host\s+" ~/.ssh/config | awk '{print $2}')
# Get the current word being completed
local current_word="${COMP_WORDS[COMP_CWORD]}"
# Set the list of possible completions to the list of hosts
COMPREPLY=($(compgen -W "${hosts}" -- "${current_word}"))
}
# Register the custom completion function for the "ec2" command
complete -F _ec2_hosts ec2
The script needs to be saved, made executable, and sourced in your .bashrc with one of these two lines:
. /path/to/ec2_bash_completion
# Or
source /path/to/ec2_bash_completion
Exit and save your .bashrc, then source it with . ~/.bashrc
. Now your completions will work!
This script doesn’t complete “start|stop”, but if I add more commands, maybe I’ll update the script.