Search code examples
javalinuxshellnashorn

Java Linux Shell Application


So I just received a task for creating a Java Shell App, without using any 3rd party libraries, and without using Runtime.exec() or ProcessBuilder APIs.

I don't want the solution (obviously I want to do this myself) but I do need a hint how to do this? I want the app to open a shell prompt which will accept various commands with usage of JDK 8 (Nashorn?).

Thanks!


Solution

  • Not really clear what you want to achieve. If you want to run a Nashhorn shell you can achieve it like this (Java 8)

    import jdk.nashorn.tools.Shell;
    public class NashornShell {
        public static void main(String[] args) {
            Shell.main(new String[]{ "-scripting"});
        }
    }
    

    When you see the Nashorn prompt jjs> you can execute Linux commands...

    jjs> $EXEC("ls");
    

    which will list the current directory (using the Linux ls command).

    ... or execute Java commands ...

    jjs> java.lang.System.out.println("foo");
    

    ... or execute JavaScript commands ...

    jjs> print("foo");
    

    For more information have a look in the nashorn guide.

    edit If you want to pass only yourCommand as parameter.

    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine engine = factory.getScriptEngine(new String[]{"-scripting"});
    String yourCommand = "ls";
    Object eval = engine.eval("$EXEC(\"" + yourCommand + "\")");
    System.out.println(eval);
    

    edit do you think that instead of Nashorn I could just use raw streams directed to the OS from JVM

    Following is possible

    Commands.java

    class Commands {
        public static void main(String[] args) {
            System.out.println("ls");
            System.out.println("whoami");
        }
    }
    

    run.sh

    #!/bin/sh
    java Commands | while read command; do
      echo
      echo "command: $command"
      $command
    done
    

    But obviously this is not to recommend when you want to execute the output of Commands:

    • your Java application has no control about the return state of the executed single commands
    • if one command wait for user input your Java application don't know it
    • your Java application has no access to the output produced by the commands
    • all commands are blindly exected
    • and some more downsides