如何从 Java 调用 Linux shell 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1410741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:46:59  来源:igfitidea点击:

How to invoke a Linux shell command from Java

javashellcommand-line

提问by Narek

I am trying to execute some Linux commands from Java using redirection (>&) and pipes (|). How can Java invoke cshor bashcommands?

我正在尝试使用重定向 (>&) 和管道 (|) 从 Java 执行一些 Linux 命令。Java 如何调用cshbash命令?

I tried to use this:

我试着用这个:

Process p = Runtime.getRuntime().exec("shell command");

But it's not compatible with redirections or pipes.

但它与重定向或管道不兼容。

采纳答案by KitsuneYMG

exec does not execute a command in your shell

exec 不会在你的 shell 中执行命令

try

尝试

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

反而。

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

编辑:: 我的系统上没有 csh,所以我改用了 bash。以下对我有用

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

回答by Tim

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

使用 ProcessBuilder 来分隔命令和参数而不是空格。无论使用何种外壳,这都应该有效:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}

回答by Evgeni Sergeev

Building on @Tim's example to make a self-contained method:

以@Tim 的示例为基础制作一个自包含的方法:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Shell {

    /** Returns null if it failed for some reason.
     */
    public static ArrayList<String> command(final String cmdline,
    final String directory) {
        try {
            Process process = 
                new ProcessBuilder(new String[] {"bash", "-c", cmdline})
                    .redirectErrorStream(true)
                    .directory(new File(directory))
                    .start();

            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null )
                output.add(line);

            //There should really be a timeout here.
            if (0 != process.waitFor())
                return null;

            return output;

        } catch (Exception e) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.

            return null;
        }
    }

    public static void main(String[] args) {
        test("which bash");

        test("find . -type f -printf '%T@\\t%p\\n' "
            + "| sort -n | cut -f 2- | "
            + "sed -e 's/ /\\\\ /g' | xargs ls -halt");

    }

    static void test(String cmdline) {
        ArrayList<String> output = command(cmdline, ".");
        if (null == output)
            System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
        else
            for (String line : output)
                System.out.println(line);

    }
}

(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)

(测试示例是一个命令,它按时间顺序递归地列出目录及其子目录中的所有文件。)

By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.

顺便说一句,如果有人能告诉我为什么我需要四个和八个反斜杠,而不是两个和四个,我可以学到一些东西。比我所计算的还要多一层无法逃避的事情发生。

Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.

编辑:刚刚在 Linux 上尝试了相同的代码,结果我在测试命令中需要一半的反斜杠!(即:预期的 2 和 4 数量。)现在它不再只是奇怪,而是一个可移植性问题。