Enable tab completion for known SSH hosts

complete -W "$(echo `cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ssh

By: sammcj
2011-06-01 23:21:06

8 Alternatives + Submit Alt

What Others Think

Useful. But we can make it better. Lose the "cat" and pipe the file straight into sed. Use "sed" to delete everything after a comma or a space (no need for cut). Then use "sort -u" to remove duplicates. "uniq" will only work if the list is already sorted. I've dropped your final "grep" -- I'm sorry, I don't understand it. When do you see "[" in your hostnames? complete -W "$(echo $(sed 's/[, ].*//' < ~/.ssh/known_hosts | sort -u))" ssh
flatcap · 572 weeks and 4 days ago
But your command and my improvement are static -- the list of hostnames is only read once. What you really need is something that reads known_hosts every time. Then, if you ssh to a new host, the name is added to known_hosts and the completion automatically picks it up. This function does the trick. It's not a one-liner any more :-) _ssh_complete () { local cur _get_comp_words_by_ref cur COMPREPLY=( $( compgen -W "$(echo $(sed 's/[, ].*//' < ~/.ssh/known_hosts | sort -u))" -- "$cur" ) ) } complete -F _ssh_complete ssh
flatcap · 572 weeks and 4 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: