Apache Commons logo Apache Commons Exec

Building the command line

You have two ways to create the command line to be executed

  • parsing the entire command line string
  • building the command line incrementally

General Considerations

No matter which approach you are using commons-exec does change your command line arguments in the following two cases

  • when the executable contains forward or backward slashes
  • when a command line argument contains an unquoted string

The following executable arguments


will be translated under Windows to


Parsing the entire command line string

Parsing the command line string is easy to use but you might run into problems when tackling complex scenarios. Therefore this functionality was deprecated in the Ant Exec task.

Let's have a look at few examples you would like to stick to parsing entire command line strings

Spaces in command line arguments

Here we would like to invoke a batch file which contains spaces in the path

cmd.exe /C c:\was51\Web Sphere\AppServer\bin\versionInfo.bat

Due to the space in the file name we have to quote the file name either with single or double quotes otherwise it falls apart into two command line arguments c:\was51\Web and Sphere\AppServer\bin\versionInfo.bat.

String line = "cmd.exe /C 'c:\\was51\\Web Sphere\\AppServer\\bin\\versionInfo.bat'";

Building the Command Line Incrementally

This is the recommended approach and caters also for pre-quoted command line argument.

A simple example

Now we would like to build the following command line

runMemorySud.cmd 10 30 -XX:+UseParallelGC -XX:ParallelGCThreads=2

using the following code snippet

CommandLine cmdl = new CommandLine("runMemorySud.cmd");

A complex example

Now let's have a look at the following command line found somewhere in the internet

dotnetfx.exe /q:a /c:"install.exe /l ""\Documents and Settings\myusername\Local Settings\Temp\netfx.log"" /q"

The following code snippet builds the command line using pre-quoted arguments and variable expansion

File file = new File("/Documents and Settings/myusername/Local Settings/Temp/netfx.log");
Map map = new HashMap();
map.put("FILE", file);

cmdl = new CommandLine("dotnetfx.exe");
cmdl.addArgument("/q:a", false);
cmdl.addArgument("/c:\"install.exe /l \"\"${FILE}\"\" /q\"", false);

For the Desperate

When crafting a command line it would be really helpful to see what happens to your command line arguments. The following scripts can be invoked to print your command line arguments for Unix

while [ $# -gt 0 ]
    echo "$1"

and for Windows

IF [%1]==[] GOTO Continue
    @ECHO "%1"