[Solved] How to run a shell script .sh file in java


it is much advisable to use the Process Builder. It is really built for this kind of tasks.

Your program permisions.sh is not an executable as Java understands it, even though the operating system understands it as an executable file.

You need to inform Java that the bash shell (or some other shell) is needed to execute your command. eg. /bin/bash is the path to the program that can run or execute your script. With that said you follow this code snippet bellow to fix get that working.

public class FilePermission extends AbstractMediator
{

  public boolean mediate(MessageContext context) { 
      try {
      File oldfile =new File("/ggmd/files/uploads/FIle contract1.csv");
        File newfile =new File("/ggmd/files/uploads/contract1.csv");

        if(oldfile.renameTo(newfile)){
            System.out.println("Rename succesful");
        }else{
            System.out.println("Rename failed");
        }

private final String commandPath = "/bin/bash";

private final String scriptPath = "/opt/file/contracts/tst/permissions.sh";


try {
        Process execCommand = new ProcessBuilder(commandPath, scriptPath).start();
        execCommand.waitFor();
    } catch (IOException e) {
        // handle exceptions
        System.out.println(e.getMessage());
    } catch (InterruptedException e) {
        System.out.println(e.getMessage());
    }


    return true;
  }
}

Please note that the above code may need some modification especially if your script(permissions.sh) may depend on the current working directory. with the above the working directory of the java code is being used.

but can be changed by calling the directory(File directory) method on the process object. then pass the new working directory path to it. In this case

Process execCommand = new ProcessBuilder(commandPath, scriptPath).directory(new File("/some/directory/to/be/used/")).start();

You can also call the execCommand.getErrorStream(); or execCommand.getInputStream(); where needed.

10

solved How to run a shell script .sh file in java