Skip to content

Instantly share code, notes, and snippets.

@nhthai2005
Last active January 30, 2024 14:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nhthai2005/f956a0e6cfc3b38f72f0df1a239a4e68 to your computer and use it in GitHub Desktop.
Save nhthai2005/f956a0e6cfc3b38f72f0df1a239a4e68 to your computer and use it in GitHub Desktop.
Autocomplete server names for SSH and SCP for Git Bash

Autocomplete server names for SSH and SCP for Git Bash

For ssh

1. Make a file with name ssh as following content:

_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

2. Put that script in /etc/bash_completion.d/ssh (Linux)

  • Windows: C:\Program Files\Git\usr\share\bash-completion\completions (Path in Bash like /usr/share/bash-completion/completions/ssh)

3. And then source it with the following command:

$ . /etc/bash_completion.d/ssh (if Linux)
$ . /usr/share/bash-completion/completions/ssh (if windows)
  • Or append . /usr/share/bash-completion/completions/ssh into ~/.bash_profile or ~/.bashrc, like following:
# Hong-Thai: make autocomplete for ssh
test -f /usr/share/bash-completion/completions/ssh && . /usr/share/bash-completion/completions/ssh
test -f /usr/share/bash-completion/completions/scp && . /usr/share/bash-completion/completions/scp

4. Then, append the following content into ~/.ssh/config

# Example:
 Host myubuntu
   Hostname 172.10.5.4
   User vagrant
 Host mycentos
   Hostname 192.168.99.102
   User centos
   ProxyJump gateway
   ProxyCommand=nc -X 5 -x 10.17.1.100:2500 %h %p
 Host mydebian
   Hostname 192.168.1.103
   User centos
   ProxyJump gateway

For scp

* Make a file with name scp as following content:

_scp() 
{
    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 _scp -o nospace scp

* Next steps, do the same as ssh above

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