title: How to run shell script which is stored in a String variable using Java?
body: <p>I need to execute a shell script in Java. My shell script is not in a file, it is actually stored in a String variable. I am getting my shell script details from some other application.</p>
  
  <p>I know how to execute different commands in Java as shown below:</p>
  
  <pre><code>public static void main(final String[] args) throws IOException, InterruptedException {
      //Build command 
      List&lt;String&gt; commands = new ArrayList&lt;String&gt;();
      commands.add("/bin/cat");
      //Add arguments
      commands.add("/home/david/pk.txt");
      System.out.println(commands);
  
      //Run macro on target
      ProcessBuilder pb = new ProcessBuilder(commands);
      pb.directory(new File("/home/david"));
      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);
  }
  </code></pre>
  
  <p>In my case, I will have script information in a json string variable from which I am extracting the content of script:</p>
  
  <pre><code>{"script":"#!/bin/bash\n\necho \"Hello World\"\n"}
  </code></pre>
  
  <p>Below is my code in which I am extracting script content from above json and now I am not sure how can I execute this script and also pass some parameters to it. For now, I can pass any simple string parameters:</p>
  
  <pre><code>String script = extractScriptValue(path, "script"); // this will give back actual shell script
  
  // now how can I execute this shell script using the same above program?
  // Also how I can pass some parameters as well to any shell script?
  </code></pre>
  
  <p>After executing the above script, it should print out Hello World.</p>