Host Completion in bash

Juliet Kemp
Hitting tab to complete commands and filenames is great. Extending this to hostnames is even better. (Does it show that I'm very lazy?) One way of doing this is to switch to the zsh shell, which does this and a bunch of other stuff by default. Happily, though, if you'd rather stick with bash, all is not lost.

Tip of the Trade: One way to get the most out of bash's programmable parameter completion is to set up hostname completion. Here's how to code it yourself.

bash has programmable parameter completion, so you could set hostname completion up by coding it yourself. That's not necessary, though. Instead, you can pick up the bash completion files (also available as the bash-completion package in RH, Debian and from Darwin Ports for Mac OS X).

Once you've installed that, type:

. /etc/bash_completion	
(path on a Mac is /opt/local/etc/bash_completion). Add this to your ~/.bashrc or ~/.bash_profile to load it automatically on startup. Now, try typing ssh and a couple of letters of a machine you often ssh to, then hit Tab. Bingo! You'll get either a list of options, or, if there's only one option available, the name filled in, just like with the tab-completion you're already used to.

This takes information from your .ssh/known_hosts file. It works automatically for ssh and similar commands, but you can also set other commands to use it. For example, maybe you have a script called 'update' which updates a particular host. Type:

complete -F _known_hosts update
and you should now be able to tab-complete hosts with that, as well. (If you have problems, try specifying its full path.)

To investigate programmable completion options more, complete -p will list all the currently available completions.

This article was originally published on Feb 23, 2009
Page 1 of 1

Thanks for your registration, follow us on our social networks to keep up-to-date