benjiPosted under Java.

One of the nice features of Nashorn is that you can write shell scripts in JavaScript.

It supports #!s, #comments, reading arguments, and everything there’s a Java library for (Including executing external processes obviously)

Here’s an example

#!/home/benji/nashorn7/bin/nashorn
#this is a comment
 
print('I am running from ' + __FILE__);
 
var name = arguments.join(' ');
print('Hello ' + name);
var runtime = Packages.java.lang.Runtime.getRuntime();
runtime.exec('xmessage hello ' + name);

Nashorn also comes with an interactive shell “jjs”, which is great for trying things out quickly.

If you want to run the scripts with Java7 instead of Java8 you’ll need to add Nashorn to the java boot classpath. Simply modify the “bin/nashorn” script and append

-J-Xbootclasspath/a:$NASHORN_HOME/dist/nashorn.jar

Tags:

Leave a Reply

  • (will not be published)