Skip to content

Instantly share code, notes, and snippets.

@aliang
Created June 14, 2011 07:14
Show Gist options
  • Save aliang/1024466 to your computer and use it in GitHub Desktop.
Save aliang/1024466 to your computer and use it in GitHub Desktop.
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
@robinbowes
Copy link

I tweaked it to work when you have multiple known_hosts files, and multiple config files:

# shellcheck shell=bash

# Add tab completion for SSH hostnames
#
# Based on this gist: https://gist.github.com/aliang/1024466
#
# Search in:
#  - ~/.ssh/config
#  - ~/.ssh/config.d/*config
#  - ~/.ssh/*known_hosts

_complete_ssh_hosts ()
{
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  comp_ssh_hosts=$(
    sort -u < <(
      awk '{split($1,aliases,","); if (aliases[1] !~ /^\[/) print aliases[1]}' < <(
        # list all known_hosts files, ignoring blank lines and comments
        # awk code taken from https://stackoverflow.com/a/17396799
        awk '!/^ *#/ && NF' < <(cat ~/.ssh/*known_hosts)
      )
      awk '/^Host/ && $2 !~ /[*]/ {print $2}' <(
        cat ~/.ssh/{config,config.d/*config}
      )
    )
  )
  COMPREPLY=( $(compgen -W "$comp_ssh_hosts" -- $cur) )
  return 0
}
complete -F _complete_ssh_hosts ssh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment