How To Autocomplete SSH Hosts

ahmedmusallam profile image Ahmed Musallam ・2 min read

So you know about SSH config file, there are several awesome articles on the subject:

This awesome article

and this one that covers some tips and tricks

Now, with all of that, you still have to remember the full host entry to connect and it will not be autocompleted for you.

let's say I have the following in my config file:

Host unicorn-one
  User amusallam
  IdentityFile ~/.ssh/id_rsa

Host unicorn-two
  User amusallam
  IdentityFile ~/.ssh/id_rsa

Host unicorn-three
  User amusallam
  IdentityFile ~/.ssh/id_rsa

and now I type ssh unicorn into terminal and hit ⇥ Tab, it will not auto complete...

sad gif

But fear not! for I have what your heart desires!

Autocomplete Script

I've only tried this on MacOs.

courtesy of this stackexchange answer:

Found it!!

It seems that in Ubuntu the entries in ~/.ssh/known_hosts are hashed, so SSH completion cannot read them. This is a feature, not a bug. Even by adding HashKnownHosts no to ~/.ssh/config and /etc/ssh/ssh_config I was unable to prevent the host hashing.

However, the hosts that I am…

add the following file: /etc/bash_completion.d/ssh whose contents:

    local cur prev opts
    opts=$(grep '^Host' ~/.ssh/config ~/.ssh/config.d/* 2>/dev/null | grep -v '[?*]' | cut -d ' ' -f 2-)

    COMPREPLY=( $(compgen -W "$opts" -- ${cur}) )
    return 0
complete -F _ssh ssh

Then load that file: in your ~/.bash_profile, add:

## load ssh autocompletion
. /etc/bash_completion.d/ssh

and reload by running source ~/.bash_profile or just terminate your terminal and reopen it.

and voila!

(The flashes you see below are me hitting ⇥ Tab)

Alt Text

easy peasy!

Extra helpful alias

if you want to see a list of all your hosts, you can add this alias to your .bash_profile:

# list all "Host" and "HostName" lines, then remove the strings: "Host " and "HostName "
alias sshhosts="grep -w -i -E 'Host|HostName' ~/.ssh/config | sed 's/Host //' | sed 's/HostName //'"

reload by running source ~/.bash_profile or just terminate your terminal and reopen it.

then you can run it:


from unicorn example above, this prints:


Posted on by:

ahmedmusallam profile

Ahmed Musallam


Lead Developer: Adobe Experience Manager. Father of one. Minnesota. Occasionally write here: ahmedmusallam.com and there: https://blogs.perficientdigital.com/author/amusallam/


markdown guide