I am trying to execute some Linux commands from Java using redirection (>&) and pipes (|). How can Java invoke csh
or bash
commands?
I tried to use this:
Process p = Runtime.getRuntime().exec("shell command");
But it's not compatible with redirections or pipes.
We've used the Runtime and ProcessBuilder classes to do this. Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.
You can use java. lang. Runtime. exec to run simple code.
Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Test { public static void main(final String[] args) throws IOException, InterruptedException { //Build command List<String> commands = new ArrayList<String>(); commands.add("/bin/cat"); //Add arguments commands.add("/home/narek/pk.txt"); System.out.println(commands); //Run macro on target ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File("/home/narek")); pb.redirectErrorStream(true); Process process = pb.start(); //Read output StringBuilder out = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null, previous = null; while ((line = br.readLine()) != null) if (!line.equals(previous)) { previous = line; out.append(line).append('\n'); System.out.println(line); } //Check result if (process.waitFor() == 0) { System.out.println("Success!"); System.exit(0); } //Abnormal termination: Log command parameters and output and throw ExecutionException System.err.println(commands); System.err.println(out.toString()); System.exit(1); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With