Skip to content Skip to sidebar Skip to footer

What Is The Java Equivalent Of Pythons's Subprocess Shell=true Property?

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

Solution 1:

Two possible ways:

  1. Runtime

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

    ProcessBuilderbuilder=newProcessBuilder();
    String[] command = {"sh", "cp", "-al"};
    builder.command(command);
    ProcessshellP= 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

Post a Comment for "What Is The Java Equivalent Of Pythons's Subprocess Shell=true Property?"