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.

Answer from Renรฉ Link on Stack Overflow
Top answer
1 of 8
30

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.

2 of 8
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;
}
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - Quick guide to how to two ways of running a shell command in Java, both on Windows as well as on UNIX.
Discussions

directory - How to run Java program in Bash script and give it one argument? - Unix & Linux Stack Exchange
That Java program need "directory path" of that chosen folder, as argument. ... https://stackoverflow.com/questions/14601430/how-to-run-a-c-program-in-bash-script-and-give-it-2-arguments ... Do you only need to know the command to run the java program or are you asking for the complete solution? More on unix.stackexchange.com
๐ŸŒ unix.stackexchange.com
October 19, 2015
Running a bash shell script in java - Stack Overflow
I want to run a shell script from my program below but it doesn't seem to do anything. I've run the same command directly in the linux terminal and it works fine so I'm guessing it's my java code. ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
linux - Execute bash command within java program - Stack Overflow
So, when I click on the .jar file, I would like to that the program open a bash, and execute the command (java -jar ...), to execute another part of the program. ... To understand this, you first need to understand how you would run that command at a shell prompt. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can't run java in bash script
You're replacing the PATH variable; that's a system variable that contains a list of paths that the OS looks in when you try and run a command. One of the paths in that list will be where the java binary is located which is why the OS suddenly can't find it. Change PATH= to something else and you should be good More on reddit.com
๐ŸŒ r/bioinformatics
3
2
September 8, 2021
๐ŸŒ
Medium
frankielc.medium.com โ€บ run-bash-commands-from-java-8319fbff23f7
Run bash commands from Java - Frankie - Medium
March 1, 2023 - As one of Java paradigms is โ€œwrite once, run anywhereโ€, and calling external software makes that much more complicated, youโ€™ll want to steer away from it as much as possible. However, sometimes thereโ€™s really no other viable option. The example below shows how to ping a host and capture both the standard and the error output streams. String cmd = "ping -c 4 -W 1 8.8.8.8" try { ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); pb.redirectErrorStream(true); Process process = pb.start(); process.waitFor(10, TimeUnit.SECONDS); try (BufferedReader br = new BufferedReader( new Input
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this tutorial, we'll cover how to execute shell commands, bat and sh files in Java. We'll be covering examples for all exec() and ProcessBuilder approaches.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Run Bash Command On Remote Machine From Java - YouTube
In this video I showed how you run command or bash script from java applicationcode : https://github.com/lynas/bash-command-remote-machine-javaother videos: ...
Published ย  November 23, 2018
Find elsewhere
๐ŸŒ
Stack Exchange
unix.stackexchange.com โ€บ questions โ€บ 237104 โ€บ how-to-run-java-program-in-bash-script-and-give-it-one-argument
directory - How to run Java program in Bash script and give it one argument? - Unix & Linux Stack Exchange
October 19, 2015 - I know about that Java thingy., in fact, it's not about Java - but how to make the OS, run a program, in a way that I want, with all requirements supplied. ... There is Caja-actions Configration tool to add the open with ABC in context menu. There is command tab in Caja Action tool, there you can provide the script path and the directory argument.
๐ŸŒ
ExtraVM
thishosting.rocks โ€บ how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - Runtime.exec() is a simple high-level class, not customizable at the moment but available in every Java application. It gives the possibility for the application to communicate within its environment. The exec() method is for executing commands directly or running .bat/.sh files.
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - The .sh only contains one line of shell script ( a simple โ€˜ pm enable {packagename} โ€˜ command ). Would it be easier to put the command somewhere, or use the โ€˜ test.sh โ€˜ var? The best option is to make a link from text in an existing app (decompiled and manipulated in .smali dorm, via โ€˜APKEditor)โ€ฆ This was posted on a couole of sites, without solution. Hope you can help; cheers! ... Hello, When i run java from terminal than my shell command executes.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-write-a-bash-script-to-run-a-Java-program-with-a-series-of-arguments-automatically
How to write a bash script to run a Java program with a series of arguments, automatically - Quora
Answer: Enter the following in a text file using a text editor. Naturally, substitute the name of your program and the accordant arguments. Type it exactly the way you would do it on a shell commandline. Lets say you name it [code ]myProgram.sh[/code] : [code]#! /bin/bash # since this is a java ...
๐ŸŒ
Netjstech
netjstech.com โ€บ 2016 โ€บ 10 โ€บ how-to-run-shell-script-from-java-program.html
How to Run a Shell Script From Java Program | Tech Tutorials
This post talks about how you can execute a shell script from a Java program. If you have a shell script say test.sh then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).
๐ŸŒ
AutoHotKey
wasteofserver.com โ€บ call-external-command-from-java
Run bash commands from Java - Waste of Server
March 1, 2023 - As one of Java paradigms is "write once, run anywhere", and calling external software makes that much more complicated, you'll want to steer away from it as much as possible. However, sometimes there's really no other viable option. The example below shows how to ping a host and capture both the standard and the error output streams. String cmd = "ping -c 4 -W 1 8.8.8.8" try { ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); pb.redirectErrorStream(true); Process process = pb.start(); process.waitFor(10, TimeUnit.SECONDS); try (BufferedReader br = new BufferedReader( new InputStreamRe
๐ŸŒ
Princeton CS
introcs.cs.princeton.edu โ€บ java โ€บ 15inout โ€บ linux-cmd.html
Java and the Linux Command Line
To configure Java, you will need to know which shell you are running. In case you don't know, type the following command: [wayne] ~> echo $SHELL Your shell will likely be bash, tcsh, sh, or ksh.
๐ŸŒ
Reddit
reddit.com โ€บ r/bioinformatics โ€บ can't run java in bash script
r/bioinformatics on Reddit: Can't run java in bash script
September 8, 2021 -

I was trying to re-use one of my old scripts for trimmomatic but I was getting error "java: command not found".

I realised that it will work if the java command is first. It stops if there is anything above it, e.g

This works:

#!/bin/bash
java --version
PATH=/media/msz/Arabidopsis_project/scripts

$ ./test.sh 
openjdk 11.0.11 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.18.04)
OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.18.04, mixed mode, sharing)

This won't :

#!/bin/bash
PATH=/media/msz/Arabidopsis_project/scripts
java --version

$ ./test.sh 
./test.sh: line 3: java: command not found

Anyone have any idea what is going on?

Thanks for your help!

๐ŸŒ
Kevin Boone
kevinboone.me โ€บ exec.html
How to run a shell script from a Java application - Kevin Boone
To invoke the shell to run the script, we might try something like this: ... The -c switch tells the shell to process the next argument as a command.