Cool bash completion trick…

Here’s a cool trick for you folks…

If you regularly ssh to a set of servers in your server farm, but don’t like having to type out the full hostname on the command line (or can’t remember all the ip addresses), I’ve got a tip for you.

I’m sure you already know that you can type a part of a filename on the command line, and have bash complete the name.  For instance, you would type:

vi /etc/hos[tab]

…and the tab key completes the word “host” (pressing tab twice shows the remaining matching options that start with /etc/hosts, including /etc/hosts).  But did you know that bash completion can work for more things that just the filesystem?  Well, you do now.

So now let’s apply this capability to ssh, since this is something many of us commonly use.  Normally if you are trying to ssh to a server, you probably type something like this:

ssh longservernamethatyoudontwanttotype

So, if you happen to have all your servers  in your local /etc/hosts file, we can add them to the bash shell’s tab completion capability with the following command:

complete -W "`awk '{ print $2 }' /etc/hosts`" ssh

…and be very careful there to note the back-ticks and double-quotes.  In case you are wondering, what this is doing is to take the second column of your hosts file and put them into a list for completion of any ssh command.  Of course, you could add this to a startup script or some such, but I’m not going into that here for the sake of brevity.  Anyway, now if you type:

ssh long[tab]

…then the rest of the long servername will be completed there on the line.  Is that cool or what?

Alternately, if you happen to have the servernames listed in a textfile, or if you need to prefix your ssh connections with a username, you could create that server list file like this (with or without the username prefix, depending on how you wish to connect):


…and so on.  This way, the tab completion will include your username prefix. And to utilize this particular file, you would enter something like this (of course, pointing to your particular server list, not mine):

complete -W "`cat /home/jpavlov/serverlist.txt`" ssh

…and again, be careful with the quotes and back-ticks.

I hope this makes your life easier folks, it sure has helped me… And if you haven’t figured it out already, this process applies to just about any program you want.  And, you can actually use more precise functions instead of the command method I describe here, but that’s a lot more complex than I wanted to get into in this post.  Make sure to check out the already-existing function files at /etc/bash_completion and check out complete --help for more details…



Leave a Comment

Your email address will not be published. Required fields are marked *