0

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 ?

4
  • 5
    Can you check that your bash file is in the correct path relatively? You may try to change the path to an absolute one and then check it. Commented Feb 18, 2019 at 9:33
  • if the program is in the expected path, make sure that all pathes inside of the bash file are correct and all programs are in path Commented Feb 18, 2019 at 9:36
  • 1
    the path of my bash file is correct yes Commented Feb 18, 2019 at 9:48
  • @sali333 please checkout the latest answer. Commented Feb 18, 2019 at 17:54

3 Answers 3

2
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?

Sign up to request clarification or add additional context in comments.

4 Comments

The file is in my desktop
If you are using Window. In order to execute bash file, you need input full of path Ex: C:/Users/path/to/bash
I m using linux
Please change code to Runtime.getRuntime().exec(new String[]{"sh", "-c", "/home/username/Desktop/bash"});
1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.