33

I have the following class. It allows me to execute commands through java.

public class ExecuteShellCommand {

public String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader = 
                        new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";           
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

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

    return output.toString();

}

}

When I run commands, the result of the previous command isn't saved. For example:

public static void main(String args[]) {

    ExecuteShellCommand com = new ExecuteShellCommand();
    System.out.println(com.executeCommand("ls"));
    System.out.println(com.executeCommand("cd bin"));
    System.out.println(com.executeCommand("ls"));

}

Gives the output:

bin
src


bin
src

Why doesn't the second 'ls' command show the contents of the 'bin' directory?

2
  • See also When Runtime.exec() won't for many good tips on creating and handling a process correctly. Then ignore it refers to exec and use a ProcessBuilder to create the process. Nov 9, 2014 at 23:26
  • Hello. I tried to use your class to execute Bash- Commands in my Java application, but when I run the command "cat" it returns null...
    – Zanidd
    Sep 5, 2017 at 7:25

8 Answers 8

29

You start a new process with Runtime.exec(command). Each process has a working directory. This is normally the directory in which the parent process was started, but you can change the directory in which your process is started.

I would recommend to use ProcessBuilder

ProcessBuilder pb = new ProcessBuilder("ls");
pb.inheritIO();
pb.directory(new File("bin"));
pb.start();

If you want to run multiple commands in a shell it would be better to create a temporary shell script and run this.

public void executeCommands() throws IOException {

    File tempScript = createTempScript();

    try {
        ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString());
        pb.inheritIO();
        Process process = pb.start();
        process.waitFor();
    } finally {
        tempScript.delete();
    }
}

public File createTempScript() throws IOException {
    File tempScript = File.createTempFile("script", null);

    Writer streamWriter = new OutputStreamWriter(new FileOutputStream(
            tempScript));
    PrintWriter printWriter = new PrintWriter(streamWriter);

    printWriter.println("#!/bin/bash");
    printWriter.println("cd bin");
    printWriter.println("ls");

    printWriter.close();

    return tempScript;
}

Of course you can also use any other script on your system. Generating a script at runtime makes sometimes sense, e.g. if the commands that are executed have to change. But you should first try to create one script that you can call with arguments instead of generating it dynamically at runtime.

It might also be reasonable to use a template engine like velocity if the script generation is complex.

EDIT

You should also consider to hide the complexity of the process builder behind a simple interface.

Separate what you need (the interface) from how it is done (the implementation).

public interface FileUtils {
    public String[] listFiles(String dirpath);
}

You can then provide implementations that use the process builder or maybe native methods to do the job and you can provide different implementations for different environments like linux or windows.

Finally such an interface is also easier to mock in unit tests.

5
  • In createTempScriptYou(), you need to close the file before returning it.
    – Fabien
    Dec 27, 2015 at 19:27
  • @Fabien You're right. I added a line that closes the PrintWriter. As consequence the underlying readers and streams will be closed as well.
    – René Link
    Jan 5, 2016 at 7:50
  • can I execute multiple commands without creating temporary file? May 5, 2016 at 9:23
  • I needed to add a InterruptedException to throws to satisfy the compiler (Java 8)
    – Michael
    Apr 3, 2017 at 11:48
  • Should I see the standard error of the ls command? I do not.
    – the_prole
    Mar 11, 2019 at 21:20
12

You can form one complex bash command that does everything: "ls; cd bin; ls". To make this work you need to explicitly invoke bash. This approach should give you all the power of the bash command line (quote handling, $ expansion, pipes, etc.).

/**
 * Execute a bash command. We can handle complex bash commands including
 * multiple executions (; | && ||), quotes, expansions ($), escapes (\), e.g.:
 *     "cd /abc/def; mv ghi 'older ghi '$(whoami)"
 * @param command
 * @return true if bash got started, but your command may have failed.
 */
public static boolean executeBashCommand(String command) {
    boolean success = false;
    System.out.println("Executing BASH command:\n   " + command);
    Runtime r = Runtime.getRuntime();
    // Use bash -c so we can handle things like multi commands separated by ; and
    // things like quotes, $, |, and \. My tests show that command comes as
    // one argument to bash, so we do not need to quote it to make it one thing.
    // Also, exec may object if it does not have an executable file as the first thing,
    // so having bash here makes it happy provided bash is installed and in path.
    String[] commands = {"bash", "-c", command};
    try {
        Process p = r.exec(commands);

        p.waitFor();
        BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";

        while ((line = b.readLine()) != null) {
            System.out.println(line);
        }

        b.close();
        success = true;
    } catch (Exception e) {
        System.err.println("Failed to execute bash with command: " + command);
        e.printStackTrace();
    }
    return success;
}
5

Each invocation executes in its own shell. Thus the "cd" of the 2nd invocation is not seen by the 3rd.

See: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String).

This states that the command is run in a separate process. Thus you have spawned 3 processes.

If you want all 3 in the same process, try this:

com.executeCommand("ls; cd bin; ls");
3
  • Is there a way to execute a series of commands in the same context?
    – mickzer
    Nov 9, 2014 at 16:57
  • Let me rephrase my question.. Is there a way to execute a series of commands in the same context one after the other? For example would it be possible to take a series of user inputs and pass them into a shell process?
    – mickzer
    Nov 9, 2014 at 17:00
  • com.executeCommand("ls; cd bin; ls"); causes an IOException to raise: Cannot run program "ls;": error=2, No such file or directory
    – djthoms
    Nov 6, 2015 at 0:43
2

each command you are running has its own bash shell, so once you cd to that directory and for next command you are opening new bash shell

try changing your command to

ls bin
3
  • 1
    Is there a way to execute a series of commands in the same context?
    – mickzer
    Nov 9, 2014 at 16:57
  • 1
    You can wrap them in a bash script and invoke it, also use ProcessBuilder instead of Runtime
    – jmj
    Nov 9, 2014 at 16:59
  • 1
    Minor correction, as written in the question the commands are executed without a shell. The programs specified are simply executed in a forked process.
    – Dev
    Nov 9, 2014 at 17:42
1

Each command is executed individually. They dont share the context.

1
  • 1
    Is there a way to execute a series of commands in the same context?
    – mickzer
    Nov 9, 2014 at 16:57
1

for future reference: running bash commands after cd , in a subdirectory:

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

/*

$ ( D=somewhere/else ; mkdir -p $D ; cd $D ; touch file1 file2 ; )
$ javac BashCdTest.java && java BashCdTest
 .. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file1
 .. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file2
 .. stderr: /bin/ls: cannot access isnt_there: No such file or directory
 .. exit code:2

*/
class BashCdTest
    {
    static void execCommand(String[] commandArr)
        {
        String line;
        try
            {
            Process p = Runtime.getRuntime().exec(commandArr);
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = stdoutReader.readLine()) != null) {
                // process procs standard output here
                System.out.println(" .. stdout: "+line);
                }
            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((line = stderrReader.readLine()) != null) {
                // process procs standard error here
                System.err.println(" .. stderr: "+line);
                }
            int retValue = p.waitFor();
            System.out.println(" .. exit code:"+Integer.toString(retValue));
            }
        catch(Exception e)
            { System.err.println(e.toString()); }
        }

    public static void main(String[] args)
        {
        String flist = "file1 file2 isnt_there";
        String outputDir = "./somewhere/else";
        String[] cmd = {
            "/bin/bash", "-c",
            "cd "+outputDir+" && /bin/ls -l "+flist+" && /bin/rm "+flist
            };
        execCommand(cmd);
        }
    }
1

You could use the bash command "pmset -g batt" like in the method bellow witch returns the battery percentage

public int getPercentage() {
    Process process = null;
    try {
        process = Runtime.getRuntime().exec("pmset -g batt");
    } catch (IOException e) {
        e.printStackTrace();
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            process.getInputStream()));
    String s = null;
    String y = "";
    while (true) {
        try {
            if (!((s = reader.readLine()) != null)) break;
        } catch (IOException e) {
            e.printStackTrace();
        }
        y += s;
        System.out.println("Script output: " + s);
    }
    return Integer.parseInt(y.substring(y.indexOf(')') + 2, y.indexOf('%')));
}
0

This worked for me.

public static void executeBashCommand(String command) throws IOException, InterruptedException
{
    new ProcessBuilder("/bin/bash", "-c", command).inheritIO().start().waitFor();
}

and import following package.

import java.io.IOException;

and change main function to this.

public static void main(String args[]) throws Exception

Example :-

executeBashCommand("ls");

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.