sali333
sali333

Reputation: 115

execute bash script from java

I am trying to execute a bash script file , for a java program it the following way :

Runtime.getRuntime().exec("./path/to/bash"); 

But it seems to be not the correct way for doing it because it return the following exception:

 java.io.IOException: Cannot run program "./path/to/bash": error=2, No such file or directory

what is the correct way to do it ?

Upvotes: 0

Views: 5215

Answers (3)

ajith george
ajith george

Reputation: 588

Recently I used the below approach to execute a bash script.

 Process exec = getRuntime().exec("/home/user/test/test.sh");
        java.util.Scanner s = new java.util.Scanner(exec.getInputStream()).useDelimiter("\\A");
        System.out.println(s.next());

Whenever I tried getRuntime().exec("./home/user/test/test"); I got the exact error you were getting. java.io.IOException: Cannot run program "./home/user/test/test": error=2, No such file or directory. To execute any command from any directory, please follow the below approach.

String []command ={"/bin/bash","-c", "ls"};
Process exec = getRuntime().exec(command,null,new 
     File("/home/user/test"));
java.util.Scanner s = new java.util.Scanner(exec.getInputStream()).useDelimiter("\\A");
System.out.println(s.next());

Hope this is some way helpful.

Upvotes: 1

Ramesh Subramanian
Ramesh Subramanian

Reputation: 1037

To execute any bash command using java , you can use command like Runtime.getRuntime().exec("/path-to/bash -c \"rm *.foo\"") - This will remove all the files having extension .foo in the current working directory

Upvotes: 1

java.io.IOException: Cannot run program "./path/to/bash": error=2, No such file or direct

It mean path of file was wrong. Please check file path again. What folder contains this file?

Upvotes: 2

Related Questions