Bash SSH Autocomplete – Autocomplete Server Names for SSH and SCP

autocompletebashscpssh

I have a few servers configured in ~/.ssh/config, such as alpha and beta. How might I configure Bash such that the commands $ ssh alTab and $ scp file.tgz alTab autocomplete the names of the configured servers?

I don't want to add the servers to another file (i.e. a Bash array) each time one is added, as we add and remove servers regularly and the list is quite large.

This is on Kubuntu 12.10, and I do have bash-completion installed.

Best 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 interested in are also found in ~/.ssh/config. Here is a script for Bash Completion that reads the entries from that file:

_ssh() 
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    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

Put that script in /etc/bash_completion.d/ssh and then source it with the following command:

$ . /etc/bash_completion.d/ssh

I found this guide invaluable and I would not have been able to script this without it. Thank you Steve Kemp for writing that terrific guide!

Related Question