General-Purpose JavaScript Shell Scripting Example

Update This article likely requires a bit of updating to work the the newest version of xjs. The general ideas are still as described below.

Today I added an xjs File module to wrap Java file operations. I have already used this new module to clean up some of the other modules that were using Java directly.

The xjs project is about more than just building a web framework. I want to use JavaScript for some general-purpose shell scripting tasks. Here's a little example.

Deleting .svn Directories Recursively

Deleting all .svn subdirectories is something I have to do from time-to-time and I have used a bit of bash for this task. Here it is written in JavaScript.

#!/usr/bin/env xjs

require('helpers');
require('File');

var startDir        = arguments[0];
var filenameToStrip = arguments[1];
var recursive       = true;

if (arguments.length < 2 || !File.isDirectory(startDir)) {
  println("usage: strip startDir filename")
}
else {
  File.eachFile(startDir, recursive, function(file) {
    if (file.name() == filenameToStrip) {
      file.rmdir(); 
    }
  });
}

I have the code above in a file called ~/bin/strip. The ~/bin directory is in my path. I did chmod 755 ~/bin/strip to make the script an executable.

Now I can recursively remove .svn directories with the command

$ strip path/to/someDir .svn

The global arguments array contains the command line arguments after the script name.

Comments

Have something to write? Comment on this article.

Vladimir Epifanov May 8, 2008

Why not just use a bash one-liner or svn export?

Or this code is proof of concept?

Zach Leatherman May 8, 2008

Love the idea of Shell JavaScripting.

I did some googling and couldn't really find any information on XJS: What is it, and how can I learn more?

Peter Michaux May 8, 2008

Zach, xjs is a set of modules I'm developing for a server-side JavaScript framework and general-purpose JavaScript shell scripting. CPAN is the prototype for xjs. I've been blogging about xjs recently and will be adding more article. The beginning of this article should get you started.

Peter Michaux May 8, 2008

Valdimir,

The bash works fine but usually cannot remember longer bash commands so wrapping it up in a script is handy. Sometimes svn export is not available as someone may have messed up the directory structure.

Binny V A August 9, 2008

I have been using Rhino as the interpreter for my JS shell scripts. I will look into xjs.

By the way, the easiest method do remove the .svn folders should be find -name .svn -exec rm -rf {} \;

Have something to write? Comment on this article.