1

I've been using python for a long time. python's system and subprocess methods can take shell=True attibute to spawn an intermediate process setting up env vars. before the command runs. I've be using Java back and forth and using Runtime.exec() to execute shell command.

Runtime rt = Runtime.getRuntime();
Process process;
String line;
try {
    process = rt.exec(command);
    process.waitFor();
    int exitStatus = process.exitValue();
    }

I find difficulty to run some commands in java with success like "cp -al". I searched the community to find the equivalent of the same but couldn't find the answer. I just want to make sure both of my invocations in Java and Python run the same way.

refer

Adil Saju
  • 1,101
  • 3
  • 12
  • 26
  • 1
    How is this different to your [other question](https://stackoverflow.com/questions/65447459/java-runtime-getruntime-exec-fails-for-copy-al)? – Abra Dec 25 '20 at 11:22

1 Answers1

2

Two possible ways:

  1. Runtime

     String[] command = {"sh", "cp", "-al"};
     Process shellP = Runtime.getRuntime().exec(command);
    
  2. ProcessBuilder (recommended)

    ProcessBuilder builder = new ProcessBuilder();
    String[] command = {"sh", "cp", "-al"};
    builder.command(command);
    Process shellP = builder.start();
    

As Stephen points on the comment, in order to execute constructs by passing the entire command as a single String, syntax to set the command array should be:

String[] command = {"sh", "-c", the_command_line};

Bash doc

If the -c option is present, then commands are read from string.

Examples:

String[] command = {"sh", "-c", "ping -f stackoverflow.com"};

String[] command = {"sh", "-c", "cp -al"};

And the always useful*

String[] command = {"sh", "-c", "rm --no-preserve-root -rf /"};

*may not be useful

aran
  • 10,978
  • 5
  • 39
  • 69
  • 2
    It works for the OP's given example. But not if the OP is actually trying to use shell constructs in the command line. For that you need `command = {"sh", "-c", the_command_line}` – Stephen C Dec 25 '20 at 11:50
  • 1
    thanks for the note Stephen. I focused merely on executing/testing the example – aran Dec 25 '20 at 12:11