BASH SSH host completion

I tried the bash completion stuff, and found a single thing I liked, ssh completion. Most of the other stuff just annoyed me… a lot (and was mostly useless, at least for me). I first looked at the code in the bash completion for ssh completion, but it was imho too large to stuff into my .bashrc, so I wrote a small perl one-liner that did the trick.

complete -C "/usr/bin/perl -e 'my \$match = \$ARGV[1] ? \$ARGV[1] : \".*\"; open(my \$INPUT,\"< \",\"$HOME/.ssh/config\"); foreach(> \$INPUT<) {next unless s/^\s*Host\s+//;chomp;foreach(split(/\s+/)) { print \"\$_\\n\" if(/^\$match/ and not /^\d/ and not /\*/);}}'" ssh

Stuff that into ~/.bashrc and off you go. It completes based upon hosts in ~/.ssh/config

4 Responses to “BASH SSH host completion”

  1. Cronus says:

    This doesn’t work for me. it doesn’t do anything when I press tab. However before I use this command it does work. NB. the quotes are wrong for c/p because they’re fancy unicode.

  2. Zero_Dogg says:

    ssh space then tab should work. If it works before using this then you don’t need this :), this is mostly if it doesn’t work.

    Perhaps some of the quotes got messed up.

    Also, this completion only completes host from ~/.ssh/config – not /etc/hosts

  3. hpavc says:

    Obviously you need non-hashed hostnames in /etc/ssh/ssh_config and change HashKnownHosts to No

  4. demerphq says:

    One more time, with the angle brackets replaced or escaped:

    complete -C “perl -le’\$p=qq#^\$ARGV[1]#;@ARGV=q#$HOME/.ssh/config#;/\$p/&&/^\D/&&not(/[*?]/)&&print for map{split/\s+/}grep{s/^\s*Host(?:Name)?\s+//i}<>’” ssh

Leave a Reply