ssh tab completion on known_hosts

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 domain.com 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 | \
uniq

5 thoughts on “ssh tab completion on known_hosts”

  1. Oh man, i need to put that in my bashrc.. that’s so friggin useful. Right now i do poor man’s completion with Ctrl-R to get the host out of history, but this is so much better

  2. Thx for posting Nate.. I saw this and thought “awesome! I’ll have to figure out how to add that to zsh too”… then I thought about and I was pretty sure I already had host completion and I never recall setting it up… sure enough, it’s out-of-the-box zsh functionality.

    Switching shells is probably akin to switching religions, but, if you ever get a chance, you should check out zsh. It’s the best features of bash and tcsh and ksh and some of it’s own magic all rolled into one. I switched a few years ago and I’ve been in love with it ever since.

  3. Doh. No fun here: BASH_VERSION=’3.2.25(1)-release’

    $ ssh localhost
    bork@localhost’s password:
    Last login: Wed Sep 5 10:04:17 2012 from localhost.localdomain
    -bash: -o: command not found

    sed -i ‘
    s/complete/ complete/
    ‘ /etc/profile.d/bash-ssh-autocomplete.sh

    .. is still no help. It seems to be inert on my version. Maybe once we base on RHEL6 vs RHEL5 the newer bash version will have it. hope hope!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>