The Beauty of xargs

unix shell
Posted on: 2012-02-01

Every time we deploy our Rails application, our deployment tool creates a new folder based on the date and time, puts the right files in it, and when everything is ready to go, updates a symlink to point to the newest release.

Yesterday I found that I couldn't deploy because we were out of disk space. I needed to delete some of the old release folders.

When I sshed into the server and looked in the releases folder, it had a ton of folders named like this:

20120126191222
20120126193901
20120127153732
20120127171244
20120127204235
20120127204517
20120130172837
20120131152908
20120131160422

Here you see some from 2012, but they went back all the way to 2010. I wanted to delete everything older than 2012.

Enter the magic of xargs. It lets you take the output of one command and input each line of it as an argument to another command.

Here's what I did:

ls                                 # show me all the folders
ls | grep ^201[01]                 # show only the ones starting with 2010 or 2011
ls | grep ^201[01] | xargs rm -rf  # delete all those

Building up the command bit-by-bit lets me verify that I'm going to delete the right things. And xargs knocks it out.

Here's another useful example. Vim creates a temporary .swp files that sometimes don't get cleaned up. To find and delete them all out of a folder:

find . -name '*.swp' | xargs rm

Update

Turns out that this particular task is best handled by capistrano itself. See the keep_releases option.