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 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 | \

5 Comments on ssh tab completion on known_hosts

  1. ether
    2008/11/06 at 12:16 AM

    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. Mark
    2008/11/07 at 3:32 PM

    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. skw3rd
    2008/11/07 at 5:53 PM

    Nice tip Nate. Thanks!

  4. bish
    2012/09/05 at 12:25 PM

    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/

    .. 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!


1Pingbacks & Trackbacks on ssh tab completion on known_hosts

  1. […] and you get tab autocompletion of hostnames for anything in your known_hosts file. Thanks to NateĀ for this one. March 30, 2012 […]

Leave a Reply

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