Skip to content

Instantly share code, notes, and snippets.

@lifeblood
Last active March 11, 2020 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lifeblood/9840f9e802caa35f6e8482954e2459ae to your computer and use it in GitHub Desktop.
Save lifeblood/9840f9e802caa35f6e8482954e2459ae to your computer and use it in GitHub Desktop.
SSH Autocomplete

chatops: docker run --name=errbot -v /home/errbot:/errbot -d dustise/errbot-image

_ssh() 
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts=$(grep '^Host' ~/.ssh/config ~/.ssh/config.d/* 2>/dev/null | grep -v '[?*]' | cut -d ' ' -f 2-)

    COMPREPLY=( $(compgen -W "$opts" -- ${cur}) )
    return 0
}
complete -F _ssh ssh
_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

Then load that file: in your ~/.bash_profile, add:

. /etc/bash_completion.d/ssh

config别名列表

if you want to see a list of all your hosts, you can add this alias to your .bash_profile:

# list all "Host" and "HostName" lines, then remove the strings: "Host " and "HostName "
alias sshhosts="grep -w -i -E 'Host|HostName' ~/.ssh/config | sed 's/Host //' | sed 's/HostName //'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment