Running a bash shell script in java

后端 未结 3 1632
滥情空心
滥情空心 2020-12-05 05:32

I want to run a shell script from my program below but it doesn\'t seem to do anything. I\'ve run the same command directly in the linux terminal and it works fine so I\'m g

相关标签:
3条回答
  • 2020-12-05 06:20

    When you execute a script from Java it spawns a new shell where the PATH environment variable is not set.

    Setting the PATH env variable using the below code should run your script.

    String[] env = {"PATH=/bin:/usr/bin/"};
    String cmd = "you complete shell command";  //e.g test.sh -dparam1 -oout.txt
    Process process = Runtime.getRuntime().exec(cmd, env);
    
    0 讨论(0)
  • 2020-12-05 06:21

    Try this, it will work.

    String[] cmd = new String[]{"/bin/sh", "path/to/script.sh"};
    Process pr = Runtime.getRuntime().exec(cmd);
    
    0 讨论(0)
  • 2020-12-05 06:24

    You should use the returned Process to get the result.

    Runtime#exec executes the command as a separate process and returns an object of type Process. You should call Process#waitFor so that your program waits until the new process finishes. Then, you can invoke Process.html#getOutputStream() on the returned Process object to inspect the output of the executed command.

    An alternative way of creating a process is to use ProcessBuilder.

    Process p = new ProcessBuilder("myCommand", "myArg").start();
    

    With a ProcessBuilder, you list the arguments of the command as separate arguments.

    See Difference between ProcessBuilder and Runtime.exec() and ProcessBuilder vs Runtime.exec() to learn more about the differences between Runtime#exec and ProcessBuilder#start.

    0 讨论(0)
提交回复
热议问题