Question

What I'm trying to do is simply run a batch file that does some preparatory work necessary for the subsequent commands to be executed successfully (setting environment variables and stuff). To prove this I put together a sample that uses Commons Exec

public class Tester {

    public static void main(String[] args) throws Exception {
        Tester tester = new Tester();
        MyResultHandler handler = tester.new MyResultHandler();
        CommandLine commandLine = CommandLine.parse("bash");
        PipedOutputStream ps = new PipedOutputStream();
        PipedInputStream is = new PipedInputStream(ps);
        BufferedWriter os = new BufferedWriter(new OutputStreamWriter(ps));
        Executor executor = new DefaultExecutor();
        PumpStreamHandler ioh = new PumpStreamHandler(System.out, System.err, is);
        executor.setStreamHandler(ioh);
        ioh.start();
        executor.execute(commandLine, handler);
        os.write("export MY_VAR=test");
        os.flush();
        os.write("echo $MY_VAR");
        os.flush();
        os.close();
    }

    private class MyResultHandler extends DefaultExecuteResultHandler {

        @Override
        public void onProcessComplete(final int exitValue) {
            super.onProcessComplete(exitValue);
            System.out.println("\nsuccess");
        }

        @Override
        public void onProcessFailed(final ExecuteException e) {
            super.onProcessFailed(e);
            e.printStackTrace();
        }
    }
}

But that prints empty string instead of the word "test". Any clues?

Was it helpful?

Solution

Answering my own question based on feedback from another forum. The trick is to add a new line character at the end of each command like this:

 os.write("export MY_VAR=test\n");
 os.flush();
 os.write("echo $MY_VAR\n");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top