java Runtime.exec to run shell script - cannot open file

后端 未结 4 1983
悲&欢浪女
悲&欢浪女 2020-12-18 14:51

I am using Runtime.getRuntime().exec() to run a shell script from java code.

    String[] cmd = {\"sh\",  \"build.sh\", \"/Path/to my/sh file\"};
    try{
           


        
相关标签:
4条回答
  • 2020-12-18 15:34

    sh is unable to find the build.sh script. To fix this you can provide the full path to build.sh.

    0 讨论(0)
  • 2020-12-18 15:39

    The problem is that the "sh" command is unable to resolving the relative path "build.sh" to an absolute path. The most likely explanation is that "build.sh" is not in the current directory when you launch the command.

    Assuming that "/Path/to my/sh file" string is the path to the "build.sh" file, you need to run it like this:

    String[] cmd = {"/bin/sh",  "/Path/to my/sh file/build.sh"};
    try {
        Process proc = Runtime.getRuntime().exec(cmd);
        ...
    

    (.... or the equivalent using ProcessBuilder)

    On the other hand, if the "/Path/to my/sh file" string is supposed to be an argument to the "build.sh" script, then you need to run it like this:

    String[] cmd = {"/bin/sh", "/some/dir/build.sh", "/Path/to my/sh file"};
    try {
        Process proc = Runtime.getRuntime().exec(cmd);
    

    @fge's answer gives an alternative approach. He is setting the current directory for the child process before it is launched. That is the correct solution for your updated Question.

    0 讨论(0)
  • 2020-12-18 15:41

    Use a ProcessBuilder and set the working directory of the process to the directory where your script actually is:

    final ProcessBuilder pb = new ProcessBuilder("/bin/sh", "script.sh", "whatever",
        "arguments", "go", "here");
    pb.directory(new File("/path/to/directory"));
    // redirect stdout, stderr, etc
    final Process p = pb.start();
    

    See the ProcessBuilder javadoc. It contains an example of what you can do. Runtime.exec() is passé :p

    0 讨论(0)
  • 2020-12-18 15:51

    Try this:

     String[] cmd = {"sh build.sh", "/Path/to my/shfile"};
    

    and better to use ProcessBuilder

    ProcessBuilder pb = new ProcessBuilder("sh build.sh", "/Path/to my/shfile"); 
    
    0 讨论(0)
提交回复
热议问题