How to invoke a Linux shell command from Java

call shell script from java with parameters
execute terminal command from java
java execute shell command processbuilder
java execute command line windows
run terminal commands from java mac
java execute multiple shell commands
java run cmd command and get output
how to execute multiple commands in command prompt using java

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

I tried to use this:

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

But it's not compatible with redirections or pipes.

exec does not execute a command in your 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

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

How to invoke a Linux shell command from Java, With this tutorial we'll illustrate the two ways of executing a shell command from within Java code. The first is to use the Runtime class and call  Write the linux commands in the script file, once the execution is over you can read the diff file in Java. The advantage with this approach is you can change the commands with out changing java code. You need not store the diff in a 3rd file and then read from in.

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

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);
    }
}

How to Run a Shell Command in Java, How do I run a command prompt as administrator in Java? Well yes, for the best practice: put codes which are related in their own chunks. Create a Util.java for example and put it there or be more specific and say ShellUtil.java and make a general function that you can invoke any shell command there. – ambodi Apr 27 '14 at 11:30

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

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.

How to Run a Shell Script From Java Program, String cmd = "ls -al"; Runtime run = Runtime.getRuntime(); Process pr = run.exec(​cmd); pr.waitFor(); BufferedReader buf = new  Here is a simple code on how to execute a shell command from Java. As a sample command, it is used the ping command and the example was tested using Windows 10. Note: depending on your system configuration you might need permission to run a specific command.

Shell (computing), On Linux and MacOS you need to add the -c parameter to specify how many times to try. Output. Execute shell commands example Executing  With this tutorial we'll illustrate the two ways of executing a shell command from within Java code. The first is to use the Runtime class and call its exec method. The second and more customizable way, will be to create and use a ProcessBuilder instance.

Run cmd as administrator using Java Code, Suppose you want to execute "ls" command in Linux which list down all the files and directory in a folder and you want to do it using JAVA. Hi All, I need to call a java method from a shell script. I know we can use the command java ClassName to call the main method in it. But I need to call another method that is there in the class and pass an email to it. Can I use java ClassName.MethodName(email) Any help will be useful. Thanks.

Execute Shell Command From Java, Basically, you use the exec method of the Runtime class to run the command as a separate process. Invoking the exec method returns a Process  The above Java’s code will try to execute the external program (helloworld.exe) and show output in console as exit code of the external program. The sample external program, Helloworld.exe (Visual Basic) Create Runtime Object and attach to system process. In this example, execute the helloworld.exe.

Comments
  • cat and csh don’t have anything to do with one another.
  • i can understand the question for other commands, but for cat: why the hell don't you just read in the file?
  • Everyone gets this wrong first time - Java's exec() does not use the underlying system's shell to execute the command (as kts points out). The redirection and piping are features of a real shell and are not available from Java's exec().
  • stevendick: Thank you very much, I was getting problems because of redirection and piping!
  • System.exit(0) is not inside conditional checking if process is done, so it will always exit without outputting errors. Never write conditionals without braces, to avoid exactly this sort of mistake.
  • @Narek. Sorry about that. I fixed it by removing the extra \" 's Apparently they aren't needed. I don't have csh on my system, but it works with bash.
  • As others has mentioned this should be independent wether you have csh or bash, isn't it?
  • @Narek. It should, but I don;'t know how csh handles arguments.
  • Thank you. This worked. Actually I used "sh" instead of "csh".
  • Warning: this solution will very likely run into the typical problem of it hanging because you didn't read its output and error streams. For example: stackoverflow.com/questions/8595748/java-runtime-exec
  • Even after java.util.*; is properly imported I can't get above example to run.
  • @Stephan I've updated the example code above to remove the logging statements and variables that were declared outside the pasted code, and it should now compile & run. Feel free to try and let me know how it works out.
  • You should ask your question as new StackOverflow question, not as part of your answer.
  • Works with two and four on OSX / Oracle java8. Seems there is a problem with your original java environment (which you do not mention the nature of)