Search code examples
javaunixapache-commonsapache-commons-cli

Java Apache Commons CLI on Unix; > is being treated as an argument to the executable instead of a redirect


I'm trying to automate some command line tests on Windows and Unix. I'm using Java 1.6 and Apache Commons CLI 1.1 to do this. What I do in the Java code is to build up the command that I want to run using the Apache Commons CLI addArgument method. After I build the command line that I want to run, I wanted to pipe the output of the command to a file so I added the following to the end of the command

cloudscan_cmdl.addArgument(">");
cloudscan_cmdl.addArgument(cloudscanOutputFilename);

Where the cloudscanOutputFilename is the string containing the filename I want to use. This works fine on Windows, the command is built, the two arguments that redirected are added and the file is created fine. On Unix, however, it's treating the > and the filename string as additional arguments to the executable instead of as a redirect.

What can I do to get Unix to read this command as if it were typed directly like that on the command line? I have outputted the command as a string and copied and pasted that in Unix and it works as expected, but when run from the Java program the redirect isn't being treated correctly.

I've tried using the addArgument(string, boolean) version of the method as both true and as false and neither helps. This is seriously driving me crazy.


Solution

  • You're misinterpreting the purpose of the class. As stated, it's for "specifying processes to execute". It helps you pass a list of arguments to a program. It is not for telling the shell what to do. > is a redirection operator implemented by the shell. The fact that it works on Windows is an accident.

    Also, note that this is part of Apache Commons Exec, not Apache Commons CLI.

    To avoid doing the redirection yourself, your best option may be to make a simple batch file or shell script for each platform and call it.