How can Java call a shell script?

Java can invoke Shell scripts using the Runtime class or ProcessBuilder class.

  1. Invoke a shell script using the Runtime class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunShellScript {
    public static void main(String[] args) {
        try {
            // 调用Shell脚本的命令
            String command = "sh /path/to/script.sh";

            // 执行Shell脚本
            Process process = Runtime.getRuntime().exec(command);

            // 获取Shell脚本的输出结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待执行完成
            int exitCode = process.waitFor();
            System.out.println("Shell脚本执行完成,退出码:" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  1. Call a shell script using the ProcessBuilder class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class RunShellScript {
    public static void main(String[] args) {
        try {
            // 调用Shell脚本的命令
            List<String> command = List.of("sh", "/path/to/script.sh");

            // 创建ProcessBuilder对象,并设置命令
            ProcessBuilder processBuilder = new ProcessBuilder(command);

            // 设置工作目录
            processBuilder.directory(null); // 设置为null表示使用当前工作目录

            // 执行Shell脚本
            Process process = processBuilder.start();

            // 获取Shell脚本的输出结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待执行完成
            int exitCode = process.waitFor();
            System.out.println("Shell脚本执行完成,退出码:" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Note: When calling the Shell script, make sure to replace /path/to/script.sh with the actual file path of the Shell script according to the actual situation.

bannerAds