简体   繁体   中英

running nashorn using Shebang does not accept -cp option

I am trying to use a class into a jar using a Nashorn Shebang script with the -cp option (java version "1.8.0_31"). However it does not works. I have perform some test. The following shebang line works:

  • #!/usr/bin/jjs -scripting
  • #!/usr/bin/jjs -fv (returns nashorn full version 1.8.0_31-b13)

while the following not:

  • #!/usr/bin/jjs -cp ./some/lib/lib.jar will return the following error message: "-cp ./some/lib/lib.jar" is not a recognized option.
  • #!/usr/bin/jjs -scripting -fv will return the error message: "-scripting -fv" is not a recognized option. Use "-h" or "-help" to see a list of all supported options"

All options are theoretically valid. The classpath option should also works as seen on http://www.adam-bien.com/roller/abien/entry/setting_the_classpath_for_nashorn . More info about nashorn and Shebang: http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/shell.html#CHDEGHJJ

You ran into an issue which doesn't have anything to do with Nashorn nor Java. According to this answer the command line argument handling with shebang never was clearly specified and it seems to be a common behavior to treat everything encountered after the first white-space as one single argument.

So one solution would be to write a shell script containing an invocation of jjs with the actual arguments and use that shell script as the interpreter in the shebang line of your Nashorn script.

You can use -Dnashorn.args=-cp in a shebang script. See also https://bugs.openjdk.java.net/browse/JDK-8072138

As it appears you want a way to automatically add JARs to your classpath, I'll highlight a little wrapper I've written which allows you to define Maven co-ordinate dependencies (including transitives) to be added to the classpath of your script, so you can write a script using the "# dep" lines:

#!/usr/bin/env jjs-with-deps
#
# The line below is parsed by the jjs-with-deps script to build a new
# classloader in which the script is really executed, including logback
# and its transitive dependencies.
#
# dep:ch.qos.logback:logback-classic:1.1.2

var log = org.slf4j.LoggerFactory.getLogger("com.example.app.Logger");
log.info("Hello World!");

It does require Maven to be installed somewhere on your PATH, and it does slightly increase startup time (but then again, you're already starting up a JVM ;). First invocation of a given script will be much slower while any dependencies are downloaded to the local M2 repository.

Link is https://github.com/stevestorey/jjs-with-deps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM