calling shell script from Java

2019-09-05 17:25发布

问题:

I need to call shell script from java program .I'm trying to use below code but it is not working -

        ProcessBuilder pb = new ProcessBuilder("/bin/bash","/usr/local/bin/ticketer/ticketer_robot");
        pb.environment().put("$1", "test");
        pb.environment().put("$2", "testoce");
        pb.environment().put("$3", "2 - Medium");
        pb.environment().put("$4", "2 - Medium");
        pb.environment().put("$5", "Error while reading file");
        pb.environment().put("$6", "Error While reading file in Job . Please check log NotfnLOG for more details");
        pb.environment().put("$7", "testtestets");
        pb.environment().put("$8","testtesttest");
        pb.environment().put("$9", "/data/mars/logs/tesst.log");
        pb.environment().put("$10", "test@test.com");
        final Process process = pb.start();

Below is command which we are using to invoke script from unix shell -

sh /usr/local/bin/ticketer/ticketer_robot "test" "testoce" "2 - Medium" "2 - Medium" "Error while reading file" "Error While reading file in Job. Please check log for details"
 "testtestets" "testtesttest" "/data/mars/logs/tesst.log" "test@test.com"

回答1:

you should not put the arguments of the bash script in environment (thats is for environemntal variables), instead try this:

String[] command = {"/bin/bash",
                    "/usr/local/bin/ticketer/ticketer_robot", 
                    "test",
                    "testoce",
                    "2 - Medium",
                    "2 - Medium",
                    "Error while reading file",
                    "Error While reading file in Job . Please check log NotfnLOG for more details",
                    "testtestets",
                    "testtesttest",
                    "/data/mars/logs/tesst.log",
                    "test@test.com"
};

ProcessBuilder pb = new ProcessBuilder(command);
pb.start();


标签: java shell