如何动态地在Shell脚本命令中传递参数?

时间:2019-04-24 04:14:49

标签: linux unix

我想使用Java程序调用Shell脚本,并想在其中一个命令中动态传递参数?有人可以帮我用Java代码吗?

1 个答案:

答案 0 :(得分:0)

例如〜

private void execShell(String scriptPath, String ... para) {
    try {
        String[] cmd = new String[]{scriptPath};
        cmd=ArrayUtils.addAll(cmd,para);

        ProcessBuilder builder = new ProcessBuilder("/bin/chmod", "755",scriptPath);
        Process process = builder.start();
        process.waitFor();

        Process ps = Runtime.getRuntime().exec(cmd);
        ps.waitFor();

        BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        String result = sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
}