rrz0
rrz0

Reputation: 2302

Java not running bash script on Ubuntu Instance

I am trying to run a bash script on my server using Java.

The script works when tested alone using bash pm2_StopStart.bash

Running through Java I get no errors such as file not found or permission denied. These have all been solved.

I am using ProcessBuilder and followed countless examples including this link

    try {
        ProcessBuilder pb = new ProcessBuilder("/home/ec2-user/test/pm2_StopStart.bash");
        Process p = pb.start();
        //p.waitFor();
        PrintWriter writer = new PrintWriter("tmp2.txt", "UTF-8");
        writer.println("Okay. After pb.start() - " + System.getProperty("user.dir"));
        writer.close();

    } catch (IOException e) {

        try {
            PrintWriter writer = new PrintWriter("tmp.txt", "UTF-8");
            writer.println(e.getMessage());
            writer.close();
        } catch (IOException ee) {
            System.out.println(ee.getMessage());
        }
    }

No Errors whatsoever. When I input an incorrect file destination I get an error as caught in my catch block.

It seems like the script is simply not executing. Any suggestions?


#!/bin/bash

pm2 stop test
pm2 start test
pm2 log test

Upvotes: 0

Views: 119

Answers (1)

DuncG
DuncG

Reputation: 15156

Your call does not check the stdout/error streams or wait for the process. You will get more information if you change the launch to capture any errors into a file:

File stdoutFile = new File("stdout.log");
File stderrFile = new File("stderr.log");
pb.redirectOutput(stdoutFile); 
pb.redirectError(stderrFile); // or pb.redirectErrorStream(true);
Process p = pb.start();

int rc = p.waitFor();

As of JDK11 you can use this to print to file:

Files.writeString(path, "message", StandardCharsets.UTF_8);

On Linux you will need the file to start with `#!/bin/bash' or you may have to change the launch command to specify bash:

String[]cmd = new String[] {"bash", "-c", "/home/ec2-user/test/pm2_StopStart.bash"};

Upvotes: 1

Related Questions