简体   繁体   中英

How to pass arguments for a bashscript in java?

I have follwoing command to be run via my java program;

./kafka-topics.sh --zookeeper zk1.xx.com:2181,zk2.xx.com:2181,zk3.xx.com:2181 --delete --topic testTopic

I call this bash script like;

ProcessBuilder builder = new ProcessBuilder(CConstants.KAFKA_TOPIC_SH);
builder.command("--zookeeper","zk1.xx.com:2181,zk2.xx.com:21811,zk3.xx.com:2181",
                "--delete", "--topic", "testTopic");
        builder.start();

But i get following error;

java.io.IOException: Cannot run program "--zookeeper": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) ~[?:1.8.0_66]
    at

How can I run the bash script with the parameters?

Here

  • --zookeeper,--delet,e --topic are arguments
  • Others are parameters for those aruments

The error you are getting shows that your first parameter is interpreted as command name. Try this:

ProcessBuilder builder = new ProcessBuilder();
builder.command(CConstants.KAFKA_TOPIC_SH,"--zookeeper","zk1.xx.com:2181,zk2.xx.com:21811,zk3.xx.com:2181",
                "--delete", "--topic", "testTopic");
        builder.start();

when you invoke the command method you overwrite the command passed to the ProcessBuilder constructor. There is a vararg variant of the constructor where you can also pass the command arguments:

new ProcessBuilder(CConstants.KAFKA_TOPIC_SH, "--zookeeper",
   "zk1.xx.com:2181,zk2.xx.com:21811,zk3.xx.com:2181", "--delete", "--topic",   "testTopic")
   .start();

you can directly invoke the Kafka API instead of encapsulating the java command into a bash script. For example,

String[] options = new String[]{
"--create",
"--zookeeper",
"zk_host:port",
"--partitions",
"1",
"--topic",
"test",
"--replication-factor",
"1" };
TopicCommand.main(options);

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