Skip to content
Advertisement

How do I execute javascript programs from the Linux shell?

I would like to execute my javascript programs with the Rhino shell without making the first line #!/bin/sh. ‘#’ isn’t a comment character in javascript. I also don’t want to have to have a .js extension.

Is this possible? I remember reading something a long while about a method of making java programs to run without an explicit interpreter. Google has not been forthcoming, however.

Advertisement

Answer

You’ll want to use the kernel-module binfmt_misc for this. I don’t have a JS interpreter installed, but I guess the magic would be something like this for Rhino:

# If it's not included in your kernel
sudo modprobe binfmt_misc
sudo mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc

# Register the .js extension as being run by Rhino
echo ':JSScript:E::js::/path/to/rhino:' > /proc/sys/fs/binfmt_misc/register

This assumes that your scripts are happy to be run like:

 /path/to/rhino /path/to/your/script

If you need to pass any arguments to Rhino, then you’ll need to set up a wrapper. Full documentation for binfmt_misc is here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement