Monthly Archives: November 2011

Bash One Liner that uses multiple variables

I’m not sure if this particular post will come in handy to a lot of people, but my bash scripting is still pretty weak and I think the best way to commit this to memory will be to write a short post on it.

I find myself doing one line “for” statements from the command line all the time to make quick loops. Maybe I need to loop through a list of servers and delete them all, maybe I need to ping a group of servers and see if they all reply, maybe I need to build a lot of servers of different flavors at once, etc.

Whatever the reason, I have occasionally come across the need for multiple variables in my loop. For example, let’s say that I have a list of data like this:

That format may look familiar if you use the Python Command Line tool for Rackspace Cloud Servers (http://pypi.python.org/pypi/python-cloudservers/1.2)

Now let’s say that I want to create an image of the 8 servers listed above. I would usually put the above table in a tmp file, and just call out the Server ID. Something like:

This gets the job done, but it is pretty ugly. I end up with image names like “Image-of-11114”, which can be more difficult to read than “Image-of-Cherry”

Using something like the following, I can allow multiple variables in my for loop:

The whole idea is to read the full line into a variable (x) and then loops through the line assigning a specific variable to whichever fields I need.