Skip to content
Advertisement

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();
processBuilder.command("/home/otaku/Programming/data/test1.sh");
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) {
        System.out.println(output);
    } else {
        System.out.println("Script exited abnormally");
    }

} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}

The shell script file test1.sh that I am trying to execute :

#!/bin/bash
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.

Advertisement

Answer

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 ProcessBuilder.directory(File dir) to execute the bash script with the appropriate working directory
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement