For years I’ve kept a list of all the server aliases I’ve saved in my ssh config file and defined an alias called “servers” that would cat out that file and run it through sort to get an alphbetized list of all the names when I need to reference them quickly. Recently I switched to a Macbook at work and was going to recreate this but realized it was unnecessarily redundant. I already have the list in an easily parsable format in my ssh config file, no reason to maintain a separate text file of that information.

Assuming you use an ssh config file, ~/.ssh/config, you can run this in bash to get an alphabetical listing of all your server aliases using this command:

cat ~/.ssh/config | grep "Host " | cut -d " " -f 2 | sort

We use cat to read the config file out and pipe it to grep to pull out every line with “Host " (note the space). That gives us the unique aliases we’ve configured for our remote machines but it still needs to be cleaned up. We pipe that list to cut which uses the space character as the field delimiter and returns only the second field to us from the “-f 2” parameter. At the end, we pipe that output to sort which alphabetizes the final list for us.

This is useful and way more efficient than maintaining a second file but is much quicker to run as an aliased command. Assuming you maintain a bash configuration file, ~/.bashrc, you can copy and paste the line below to create an alias called servers. Please note the escaped quotation marks in the line below, if you don’t escape all of the quotation marks inside the outermost pair, it will not read the command correctly and the alias will be broken.

alias servers="cat ~/.ssh/config | grep \"Host \" | cut -d \" \" -f 2 | sort"

Once saved to ~/.bashrc, you can load the changes by running:

source ~.bashrc

You can replace “servers” above with any word you like, this is just what I prefer. Be careful not to create an alias for a command which already exists. To double check that you won’t overlap an existing command, run the following:

which <name_of_alias_you_want_to_use>
man <name_of_alias_you_want_to_use>

If neither of those commands are able to find a program of the same name, you should be safe to create your alias.