How to execute a javascript with jshell?

后端 未结 4 1013
自闭症患者
自闭症患者 2020-12-08 08:07

Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell

4条回答
  •  醉话见心
    2020-12-08 08:50

    Use

    //usr/bin/env jshell --show-version --execution local "$0" "$@"; exit $?

    as the first line of test.jsh. The test.jsh script could look like:

    //usr/bin/env jshell --show-version "$0" "$@"; exit $?
    System.out.println("Hello World")
    /exit
    

    The command line option --show-version is optional, of course, but gives immediate feedback that the tool is running.

    The extra command line option --execution local prevents jshell to spawn another VM. This speeds up launch time and if an exception is thrown by your script code, the local VM will exit.

    Consult the output of jshell --help and jshell --help-extra for more options.

    Update

    Also take a look at https://github.com/maxandersen/jbang Having fun with Java scripting, which offers a neat wrapper around running .java files from the command line.

提交回复
热议问题