Tab completion for hosts defined in ~/.ssh/config doesn't work anymore on Yosemite

I'm trying to create my ~/.ssh/config file for simplify my work life on the server connection.

In Mavericks all worked properly and with the tab I was be able to autocomplete the hostname with file like this:

Host test-host-name
    HostName 192.168.1.2
    User root

The same configuration on Yosemite have a different behavior. When I type ssh t on the shell the tab does not autocomplete the hostname.

Do someone know if is something changed in Yosemite and now I need to do something to make it work?


You can enable bash shell completion by installing bash-completion via brew:

brew install bash-completion

Then add the following to your ~/.bash_profile:

if [ -f $(brew --prefix)/etc/bash_completion ]; then
. $(brew --prefix)/etc/bash_completion
fi

Source

(Edit: brew tap homebrew/completions is deprecated as of 2018.)


I assume the shell of your Mac is bash.

You need to complete ssh command, for more detail you can read man complete

_complete_ssh_hosts ()
{
        COMPREPLY=()
        cur="${COMP_WORDS[COMP_CWORD]}"
        comp_ssh_hosts=`cat ~/.ssh/known_hosts | \
                        cut -f 1 -d ' ' | \
                        sed -e s/,.*//g | \
                        grep -v ^# | \
                        uniq | \
                        grep -v "\[" ;
                cat ~/.ssh/config | \
                        grep "^Host " | \
                        awk '{print $2}'
                `
        COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur))
        return 0
}
complete -F _complete_ssh_hosts ssh

Don't forget you need to source the file to get the new command to load in your terminal. or You can put this code in .bash_profile


From this article on MacWorld.

Copy/paste the following into ~/.bash_profile:

complete -o default -o nospace -W "$(/usr/bin/env ruby -ne 'puts $_.split(/[,\s]+/)[1..-1].reject{|host| host.match(/\*|\?/)} if $_.match(/^\s*Host\s+/);' < $HOME/.ssh/config)" scp sftp ssh

You'll then need to either restart your terminal or type source ~/.bash_profile (note that the latter will only work in your current tab).