title: Execute bash script and pass arguments with spaces from java
body: <p>I know there are a lot of post about executing commands from Java but I just can't get this to work. Here is what I'm trying to do, I have a bash script, it receives 2 arguments which might or might not have spaces, then from Java I'm executing the script and passing the arguments like this(I'm surrounding the arguments with quotes and escaping them with backslashes):</p>
  
  <pre><code>String cmd = "/opt/myScript  \"/opt/myPath1\"  \"/opt/myPath2 with spaces\"";
  Runtime rt = Runtime.getRuntime();
  rt.exec(cmd);
  </code></pre>
  
  <p>I also tried to use the <code>ProcessBuilder</code> class like this:</p>
  
  <pre><code>String myScript = "/opt/myScript";
  String myArg1= "/opt/myPath1";
  String myArg2 = "/opt/myPath2 with spaces";
  ProcessBuilder pb = new ProcessBuilder(myScript , myArg1, myArg2);
  pb.start;
  </code></pre>
  
  <p>Arguments with no spaces are received successfully but I still have problems with the second one.</p>
  
  <p>I thought the <code>ProcessBuilder</code> class would handle the spaces but seems like I'm missing something.</p>
  
  <p>I'm not sure if it has something to do, but just in case here is my script:</p>
  
  <pre><code>#!/bin/bash
  PATH=$PATH:$1
  gnome-terminal --working-directory $2
  </code></pre>
  
  <p><code>$1</code> and <code>$2</code> are the arguments sent from Java.</p>