BASH Autocompletion - Stuff… And Things…
A couple of posts back, I showed off some functions to pop up notifications when a host became pingable again or when a port became reachable. Today's (semi) quick tip is how to use BASH's autocomplete functionality add hostname autocompletion to those notifications functions.
BASH autocompletion is a system that provides tab completion of command arguments. You're familiar with it's default behavior which is to complete filenames and paths.
1 2 3 4 |
|
You can override this behavior by providing BASH with a list of possible completions. The list can be a literal list of words, or it can be a function that looks at the current environment ($PWD, user, time on day, etc) and generates context aware list.
So, what we want is a way to generate a list of hosts we know about. And, it just so happens we have such a list lying around. You know how the first time you SSH to a new server, your prompted to confirm it's identity? Well, that confirmation, along with the host's name is stored in ~/.ssh/known_hosts
. From that file we can extract a list which should cover most of the servers we care about.
The simple approach is to build a list when you login. If you Google around you'll find lots of example scripts for pulling hostnames out of known_hosts, but the most common looks like:
1 |
|
The command that setups autocompletion is complete
. When giving it a list, pass them in as an augument to the -W
option:
1 |
|
I'm capturing the output of the command with $()
and wrapping it in double quotes. The last argument is the name of the command (which can be also be a function or alias) that will use this autocompletion. Now we get this:
Read full article from BASH Autocompletion - Stuff… And Things…
No comments:
Post a Comment