-2

I have directory /tmp then I need to execute cd and go to that folder. Then I need to execute ./executeScript

Soumya RB
  • 1
  • 2

1 Answers1

0

Preparation

To start solving the problem, I created a directory /home/vulpini99/tmp. In this directory, I created the bash-script test.sh, which will open firefox for us:

firefox

Then I created a java-file named LinuxCommand.java in the directory /home/vulpini99.

Main part

cd is just an internal shell command and not an executable program, so I suggest to just use the full path of the bash-script. So the command we want to execute is

bash /home/vulpini99/tmp/test.sh.

In Java, you can use Runtime for this purpose:

import java.io.IOException;

public class LinuxCommand {

    public static void main(String[] args) {
        Runtime run = Runtime.getRuntime();
        try {
            run.exec("bash /home/vulpini99/tmp/test.sh");
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
}
  • Thanks @vulpini88... Much appreciated for your response, but I don't want to hardcode the path. Do you have any suggestions? – Soumya RB Jun 04 '20 at 10:44
  • It becomes quite complicated, if you really want to change the path. Some ideas on that can be found at https://stackoverflow.com/questions/4884681/how-to-use-cd-command-using-java-runtime/21120323. –  Jun 04 '20 at 11:17
  • Does that answer your question? –  Jun 05 '20 at 05:07
  • Thanks so much... Answer to your question, I want to construct the path instead of hardcoded, Actually, I want to deploy my application as tar format in various servers, so if I hardcode the path then it might give me FNFoundException... – Soumya RB Jun 05 '20 at 12:18
  • @SoumyaRB If my answer helped you, I would appreciate if you upvote and/or accept it. You can do this by clicking on the checkmark and the triangle over the zero if you want. –  Jun 05 '20 at 12:47