Just this week I switched to OS X and found my self wanting to really take advantage of the shell. I have always wanted to be able to do shell scripting in a language that I know well, and I finally found a solution (I know enough bash shell scripting to get in trouble).
Here is what you need to set it up.
First, make sure that you have Java installed and it is in your path (this is already setup on OS X 10.3). You can check by opening a shell / terminal window and typing:
This should output some options and info about Java. If you get an error, install and configure java.
Next, download the Rhino java files from:
I put mine in
You will probably have to create the classpath folder.
Next, you need to add the path to js.jar to your Java classpath environment variable, so Java can find it when you try to run the interpreter.
I use the bash shell, so I added the following lines to my .bash_profile in my home directory:
Notice that I point directly to the js.jar file. I also include the directory, but this is not necessary to run the js.jar file. The PATH variable was already defined. Finally, I added CLASSPATH to the export line, so it is available to my environment.
Re-initialize the shell, by either running
or just closing and re-opening the shell / terminal window.
At this point, you should be able to run the interpreter. To test, create a file named helloworld.js and add the following code:
Now run the script with the following command:
- java : runs the java command
This should then print out:
Pretty cool heh? Except that is a lot to type in to run one file. Luckily, bash provides an alias command that allows you to create aliases for commands.
So, open the ~/.bash_profile file and add the following line:
Save the file, and reinitialize it.
Now, you can run the interpreter like so:
You can find complete usage info at:
Probably the two most useful commands are:
print() which prints out to the console, and runCommand, which runs a command.
You can also pass command line arguments to the script. Here is a simple command that prints out the number of arguments passed in, as well as their values:
Save this in a file called args.js and run it like so:
This will output:
Now run it like so:
which will output:
Of course, the real power comes when you start to integrate this with existing unix commands.
I'll post more examples as I create them, in the meantime if you have any good examples, post them in the comments section.