1

I am trying to use Java to execute a shell script in Linux(Ubuntu) and trying to redirect the output to another file.

String cmd[] = {"sh", "-c", "my_dir/script.sh > new_dir/out.txt"};
Process pb = Runtime.getRuntime().exec(cmd);

However this us not working properly. I am not able to get the output to be stored in the out.txt file. Could someone suggest a way to do this properly?

3
  • 1
    does new_dir already exist? Commented Mar 5, 2018 at 6:54
  • permission to execute the script? Commented Mar 5, 2018 at 6:54
  • @Henry Yes it exists Commented Mar 5, 2018 at 6:54

2 Answers 2

2

Use a ProcessBuilder. I don't see a need for spawning an extra sh. Something like,

ProcessBuilder pb = new ProcessBuilder("my_dir/script.sh");
pb.redirectOutput(new File("new_dir/out.txt"));
Process p = pb.start();

should be all you need.

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

3 Comments

Suppose I want to also print the output of the script file as well at the same time, how would I go about doing that?
@AbhishekGangadhar Your question was how to do the shell redirect. Are you instead asking how to read process output using Java?
@Elliott Frisch How world I use tee command with Process Builder?
1

This worked for me. Use Runtime.exec()

    Process p = Runtime.getRuntime().exec("my_dir/script.sh > new_dir/out.txt");
    // Wait for execution completion 
    p.waitFor();

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.