Bash – How to fix this SSH hostname tab completion script

autocompletebashshell-script

I found the following script (for bash) that enables me to get tab completion for any hostname I've connected to (from ~/.ssh/known_hosts):

complete -W "$(echo `cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ssh

However, the problem is that the tab completion doesn't work after I've typed a username.

How can I improve this so if I type…

ssh myusername@my 

and expect it to complete "myhostname.com" it will be able to do so?

It would be even better if it could tab whole strings (user@hostname) as well, but I can live with either option. Without the first, this isn't much use unless my host username matches the local username.

Best Answer

The known_hosts file by default usually contains hashed entries which bash_completion can't parse.

You can edit your ssh_config (/etc/ssh/ssh_config) to set:

HashKnownHosts no

Then you'll probably need to clear your current known hosts file:

> ~/.ssh/known_hosts