[java] Java 코드에서 Unix 쉘 스크립트를 실행하는 방법은 무엇입니까?

Java에서 Unix 명령을 실행하는 것은 매우 간단합니다.

Runtime.getRuntime().exec(myCommand);

그러나 Java 코드에서 Unix 쉘 스크립트를 실행할 수 있습니까? 그렇다면 Java 코드 내에서 쉘 스크립트를 실행하는 것이 좋습니다.



답변

실제로 Process Builder를 살펴보십시오 . 실제로 이런 종류의 것을 위해 만들어졌습니다.

ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 Process p = pb.start();


답변

Apache Commons exec 라이브러리 도 사용할 수 있습니다 .

예 :

package testShellScript;

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
    int iExitValue;
    String sCommandString;

    public void runScript(String command){
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("permission denied.");
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        TestScript testScript = new TestScript();
        testScript.runScript("sh /root/Desktop/testScript.sh");
    }
}

추가 참조를 위해 Apache Doc 에서도 예제를 제공합니다 .


답변

Java 에서 쉘 스크립트를 실행하는 것이 Java의 정신에 있지 않다고 말하고 싶습니다 . Java는 크로스 플랫폼이어야하며 쉘 스크립트를 실행하면 사용이 UNIX로만 제한됩니다.

그렇게 말하면 Java 내에서 쉘 스크립트를 실행할 수 있습니다. 나열된 구문과 정확히 동일한 구문을 사용합니다 (내가 직접 시도하지는 않았지만 쉘 스크립트를 직접 실행 해보십시오. 그래도 작동하지 않으면 쉘 자체를 실행하고 스크립트를 명령 행 매개 변수로 전달하십시오) .


답변

나는 당신이 자신의 질문에 대답했다고 생각합니다.

Runtime.getRuntime().exec(myShellScript);

좋은 습관인지에 관해서는 Java로 할 수없는 쉘 스크립트로 무엇을하려고합니까?


답변

그렇습니다. 이것은 나를 위해 일했다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.omg.CORBA.portable.InputStream;

public static void readBashScript() {
        try {
            Process proc = Runtime.getRuntime().exec("/home/destino/workspace/JavaProject/listing.sh /"); //Whatever you want to execute
            BufferedReader read = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            try {
                proc.waitFor();
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
            while (read.ready()) {
                System.out.println(read.readLine());
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }


답변

여기 내 예가 있습니다. 이해하기를 바랍니다.

public static void excuteCommand(String filePath) throws IOException{
    File file = new File(filePath);
    if(!file.isFile()){
        throw new IllegalArgumentException("The file " + filePath + " does not exist");
    }
    if(isLinux()){
        Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", filePath}, null);
    }else if(isWindows()){
        Runtime.getRuntime().exec("cmd /c start " + filePath);
    }
}
public static boolean isLinux(){
    String os = System.getProperty("os.name");
    return os.toLowerCase().indexOf("linux") >= 0;
}

public static boolean isWindows(){
    String os = System.getProperty("os.name");
    return os.toLowerCase().indexOf("windows") >= 0;
}


답변

네 가능합니다. 좋은 연습에 대해서는 직접 코드가 아닌 파일에서 명령을 실행하는 것이 좋습니다. 당신이 할 필요가 그래서 자바는 기존의 명령 (또는 명령)의 목록 실행 .bat, .sh, .ksh… 파일을. 다음은 파일에서 명령 목록을 실행하는 예입니다 MyFile.sh.

    String[] cmd = { "sh", "MyFile.sh", "\pathOfTheFile"};
    Runtime.getRuntime().exec(cmd);