Adrian Leonhard
Adrian Leonhard

Reputation: 7360

Java ProcessBuilder + bash: "No such file or directory"

I'm trying to run bash from Java on Windows (here with the Windows Linux Subsystem, but Git Bash is the same), but even the basics are failing:

bash --noprofile --norc -c 'echo $PWD'`

In cmd.exe this works fine:

Works fine in CMD.exe

In java:

import static java.util.stream.Collectors.joining;

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

public class ProcessBuilderTest {
    public static int runBatch() {
        List<String> commandLine = new ArrayList<>();
        // both following lines have the same result
        commandLine.add("bash");
        // commandLine.add("C:\\Windows\\System32\\bash.exe"); 

        commandLine.add("--noprofile");
        commandLine.add("--norc");
        commandLine.add("-c");
        commandLine.add("'echo $PWD'");

        System.out.println("cmd: " + commandLine.stream().collect(joining(" ")));
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
            Process process = processBuilder
                .redirectErrorStream(true)
                .start();
            new BufferedReader(new InputStreamReader(process.getInputStream())).lines()
                .forEach(System.out::println);
            return process.waitFor();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (InterruptedException e) { // NOSONAR
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        runBatch();
    }
}

Running the above results in the following, and the process never exits.

cmd: bash --noprofile --norc -c 'echo $PWD'
/bin/bash: echo /mnt/c/scratch/pbtest: No such file or directory

Expected behavoir: no error and the process terminates.

Upvotes: 1

Views: 762

Answers (2)

Juan
Juan

Reputation: 5589

Using Git-bash: I changed these two lines and ir ran as expected:

// Used full path to the underlying bash.exe shell
commandLine.add("\"C:\\Program Files\\Git\\bin\\bash.exe\"");

// Removed quotes
commandLine.add("echo $PWD"); 

Ref: https://superuser.com/a/1321240/795145

Upvotes: 1

eric.v
eric.v

Reputation: 615

bash is running in cmd.exe in your windows environment

Could you have java running the following command instead ?

cmd.exe /c bash --noprofile --norc -c 'echo $PWD'

ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", 
    "/c", 
    "bash --noprofile --norc -c 'echo $PWD'");

or with the List as you initially tried

Inspired by mkyong post

Upvotes: 1

Related Questions