Skip to content
Home » Blog » SSH Autocomplete on MacOS Terminal like Linux

SSH Autocomplete on MacOS Terminal like Linux

I just moved from my ‘old’ bulky Dell XPS 17 with Linux to a MacBook Air M2. No idea if I will keep it, I will compare the Notebooks I’m testing right now in a post in the future.

I wish MacOS would be as comfortable as Linux out of the box. One thing I noticed early was the missing autocomplete when connecting to servers in your ~/.ssh/config. The tab isn’t working there.

I found a solution here:

https://gist.github.com/aliang/1024466

and will just copy&paste it for later reference.

Add auto complete to your ssh, put into your .bash_profile

_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

There’s a comment that states as follows:

you could substitute that awkward sequence of cut, sed, grep with a simple awk script:

awk '{split($1,aliases,","); if (aliases[1] !~ /^\[/) print aliases[1]}' ~/.ssh/known_hosts

So if you are a perfectionist, maybe use that one =)

You could also remove the known_hosts part if you only want to parse ~/.ssh/config.

Leave a Reply

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