Skip to content

Unable to create a folder by executing a shell script using java

I was trying to execute shell scripts using java code. The following is a sample code to demonstrate the issue :

ProcessBuilder processBuilder = new ProcessBuilder();
try {

    Process process = processBuilder.start();
    StringBuilder output = new StringBuilder();
    BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

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

    int exitVal = process.waitFor();
    if (exitVal == 0) {
    } else {
        System.out.println("Script exited abnormally");

} catch (IOException e) {
} catch (InterruptedException e) {

The shell script file that I am trying to execute :

mkdir -p -- teeh
echo 'Succesfully executed script'

I am getting echo message and was able to print in the java console indicating that the shell script is executed successfully. But no directory is being created even though the command mkdir -p — teeh is executed. If I manually execute the script file using terminal it works like a charm. I would like to know the reason behind this and a possible solution to this as well.



mkdir -p -- teeh

In this command the teeh path is a relative one rather than an absolute one: it will be created in the script’s current working directory.

Your bash script is by default executed with the working directory of your JVM, which depends on where you executed your java application from. If you’re executing your code from your IDE, by default this will be the project’s root directory. If you’re executing from the command line, it will be the directory you execute the java command from.

In any case you shouldn’t expect a /home/otaku/Programming/data/teeh directory to be created by your current code unless you run the java application from the /home/otaku/Programming/data/ directory.

There are many possible solutions, whose relevance depend on your context :

  • execute your java code from the /home/otaku/Programming/data/ directory
  • use an absolute path in your bash script
  • use cd in your bash script
  • use dir) to execute the bash script with the appropriate working directory
3 People found this is helpful