2

What I would like my code to achieve is calling one of the available two shell scripts and execute some commands whose output will be printed in a .txt file.

So far I have managed to achieve this (by calling the first script) but when I try to call the second script the terminal is not opening and the output of the commands is not appended to the .txt file.

My code is as follows:

File file = new File("res/script1.sh");
String absolutePath = file.getAbsolutePath();

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("open -a Terminal "+absolutePath);

After this execution the .txt file contains the phrase "Hello World".

My first try was to just change /script1.sh to /script2.sh as I thought the second one would append another "Hellow World" in a second line of the .txt file. This is not working as the contents of the file remain the same and the terminal is not even opening as opposed to the first case.

I have also tried to duplicate the code for the two scripts and to execute one or the other based on an input value i==1 or i==2 but with no luck.

Any thoughts why I cannot make the second script work even though it is identical to the first?

My script's code

#!/bin/sh
cd "$(dirname "$0")"
echo Hello World >> output.txt
exit
11
  • Why do you want to open a terminal and run the script instead of simply running the script in a subprocess? Commented Jun 5, 2018 at 11:53
  • I am new to shell scripting so I thought this is the correct way to do it. My first priority is to run the command and receive the output of it. Can this be achieved in a more "appropriate" way as you mentioned? Commented Jun 5, 2018 at 11:58
  • post all the code. Commented Jun 5, 2018 at 11:59
  • If the shell script has proper shebang, run the script in a subprocess. It will work. Commented Jun 5, 2018 at 12:04
  • I have also added my script's code. Commented Jun 5, 2018 at 12:05

1 Answer 1

1

You may need to run the processes in order, i.e wait for the process to finish before running next process. This is mainly because they append to the same file. To let the process finish, you must consume all its output streams. This article explains the matter in more details.

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

1 Comment

These are nice examples although I haven't tested them myself to see if it works. What I finally did was to switch to using the ProcessBuilder class and everything works fine. If there is an interest about whether my first approach can also be successful please let me know and I will give it a try.

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.