简体   繁体   中英

Execute apache-commons-exec multiple commands with semicolon

I'm using apache-commons-exec to execute some commands in a Java application.

When I execute 'ls -la /home/user' it works great.

But I need to execute something like this

./setEnvsOfTypeXXX.sh; ./setEnvsOfTypeYYY.sh; ls -la /home/user

I enter the command into the CommandLine object and it doesn't work.

It returns an empty string and -559038737 exit code.

Because the nature of the environment and the scripts (the firsts ones sets some needed environment variables); i can not put all the call into a script o I've tried many solutions (like surround all the command with quotation marks like "'" or use the PumStreamHandlet input stream) but nothing has worked so far...

Anyone has an idea ?

try

sh -c '. ./setEnvsOfTypeXXX.sh; . ./setEnvsOfTypeYYY.sh; ls -la /home/user'

As your command

Two things I'm guessing you need here.

First if you are setting enviroment variables you probably need to use . Second you want to run a shell and get the shell to exec the shell scripts and then run the following command, all in the same context

I tried this code

cmdLine = new CommandLine("/bin/bash");
cmdLine.addArgument("-c");
cmdLine.addArgument(new StringBuilder().append("'").append(command).append("'").toString());

And even with command = "ls";

There is an error

bash: ls: No such file or directory

fun fact: in windows this works ok !

        cmdLine = new CommandLine("cmd.exe");
        cmdLine.addArgument("/c");
        cmdLine.addArgument(new StringBuilder().append("\"").append(command).append("\"").toString());
        logger.info("Command win line: cmd.exe /c \""+command + "\"");

I totally out of options now !!!

I got a workarround: create a temporal sh file with the command, putting shebang on firts line and giving permissions, executing this file in one command line, get result and output, for last delete temporal file...

and it works !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM