ssh tab completion on known_hosts

written by nathan on 2008-11-05 in sysadmin

It's silly I've waited this may years to go figure this out. Many of you may already know that modern installs of OpenSSH will tab complete hostnames based on what's in the /etc/hosts file. But there is a neat little addition to your .bashrc that will tack on the ability to tab complete hostnames based on what's in ~/.ssh/known_hosts. Add this to your .bashrc:

SSH_COMPLETE=( $(cat ~/.ssh/known_hosts | \\  
cut -f 1 -d " " | \\sed -e s/,.*//g | \\  
uniq ) )complete -o default -W "${SSH_COMPLETE[*]}" ssh

All your new shells will auto complete based on what hosts you've connected to once (and therefore have entries in the known_hosts file). Any host you've never visited, well it won't be there. If you want to filter it based on certain hosts (for example, hosts in a certain domain name), just add a | grep after the uniq. If you're like me, this will save a lot of keystrokes over the next few years.

Tip: If you cut and paste my text above and it gives errors, make sure your cut-n-paste didn't change the quotes. If you want to see what it's going to use (or troubleshoot/modify), you can run this on the command line:

cat ~/.ssh/known_hosts | \\  
cut -f 1 -d " " | \\  
sed -e s/,.*//g | \\  
Tags: sysadmin