Using javascript as your shell script language.

October 16th, 2006

I’m currently developing applications for Pocket PC and Smartphone which means I spend a lot of time on a Windows box away from OS X. Recently I needed to create a bunch of event class files that were all very similar. Rather than create each one by hand I wanted to automate their creation with a script. On my mac I would use Rhino and create the script in javascript. While jscript is easy to use on Windows, I wanted to use Rhino so my scripts would work on both OS X and Windows.
Here is how I got Rhino to work on both platforms:

First, the OS X install instructions. I found instructions on Mike Chambers blog and modified them a little.

1. Download Rhino from here:http://www.mozilla.org/rhino/download.html
2. In the root directory there is a file called js.jar put it in ~/Library/Java/Extensions. If the directory doesn’t exist then create it.
3. Add this line to the .bash_profile in your home directory: alias js=’java org.mozilla.javascript.tools.shell.Main’

Rhino should now be installed. To test it:
1. Create a file called helloWorld.js that contains the line: print(”hello world”);
2. Open a terminal window, navigate to the directory where you saved helloWorld.js and type “js helloWorld.js”

Thats it. You should see “hello world” displayed in the terminal.

Now for Windows. I wanted the same functionality; type js on the command line to access Rhino.

1. Download Rhino from here:http://www.mozilla.org/rhino/download.html
2. In the root directory there is a file called js.jar put it in C:\Rhino. If the directory doesn’t exist then create it.
3. Create a file called js.bat, save it in C:\Rhino and put this script in it:

@echo off
if "%OS%"=="Windows_NT" @setlocal
if "%OS%"=="WINNT" @setlocal

set JS_FILE=%1
shift
set LINE_ARGS=%1
if ""%1""=="""" goto doneStart
shift
:setupArgs
if ""%1""=="""" goto doneStart
set LINE_ARGS=%LINE_ARGS% %1
shift
goto setupArgs

:doneStart
java -jar "C:\rhino\js.jar" %JS_FILE% %LINE_ARGS%

if "%OS%"=="Windows_NT" @endlocal
if "%OS%"=="WINNT" @endlocal

4. Add C:\rhino to your class path. (Setting classpath instructions)

Your set. You can now use javascript on both platforms for all your pragmatic scripting needs.

Leave a Reply