MAC OSX Terminal hostname auto-complete

The following script uses a function call to autocomplete hostnames dynamically, and fetches hostnames from the ~/.ssh/known_hosts, ~/.ssh/config and system-wide /etc/hosts file.
In MAC OSX, append below into your user's ~/.bash_profile, save and use new login session to take effect
_complete_hosts () {
     COMPREPLY=()
     cur="${COMP_WORDS[COMP_CWORD]}"
     host_list=`{ 
         for c in /etc/ssh_config /etc/ssh/ssh_config ~/.ssh/config
         do [ -r $c ] && sed -n -e 's/^Host[[:space:]]//p' -e 's/^[[:space:]]*HostName[[:space:]]//p' $c
         done
         for k in /etc/ssh_known_hosts /etc/ssh/ssh_known_hosts ~/.ssh/known_hosts
         do [ -r $k ] && egrep -v '^[#\[]' $k|cut -f 1 -d ' '|sed -e 's/[,:].*//g'
         done
         sed -n -e 's/^[0-9][0-9\.]*//p' /etc/hosts; }|tr ' ' '\n'|grep -v '*'`
     COMPREPLY=( $(compgen -W "${host_list}" -- $cur))
     return 0
 }
 complete -F _complete_hosts ssh
 complete -F _complete_hosts host

No comments: