Advertisement
devinteske

Simple bash completion for ssh

Mar 19th, 2020
744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.04 KB | None | 0 0
  1. #
  2. # Add to ~/.bash_profile or put in /etc/bash_completion.d/ssh
  3. # NB: May not be as "complete" as, say, /usr/share/bash-completion/completions/ssh,
  4. #     but at least it hits all the files I need and only uses a single awk to do it
  5. #     (a lot of other implementations are far less efficient or overly complicated).
  6. # NB: Supports known_hosts(5) and ssh_config(5) formats based on filename
  7. #
  8. _ssh()
  9. {
  10.     local file files=
  11.     for file in \
  12.         ~/.ssh/config ~/.ssh/config.d/* \
  13.         ~/.ssh/known_hosts /etc/ssh/known_hosts \
  14.     ; do [ -e "$file" ] && files="$files $file"; done
  15.     [ ! "$files" ] || COMPREPLY=( $( compgen -W "$( awk '
  16.         FILENAME ~ /config/ && tolower($1) == "host" {
  17.             for (n = 2; n <= NF; n++) if ($n !~ /[?*]/) print $n
  18.         }
  19.         FILENAME ~ /hosts/ {
  20.             for (n = split($1, hosts, /,/); n > 0; n--) {
  21.                 if ((len = length(hosts[n])) < 1) continue
  22.                 if ((host = hosts[n]) ~ /^\[.*\]$/)
  23.                     host = substr(host, 2, len - 2)
  24.                 print host
  25.             }
  26.         }
  27.     ' $files 2> /dev/null )" -- ${COMP_WORDS[COMP_CWORD]} ) ) || : ok
  28. }
  29. complete -F _ssh ssh
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement