简体   繁体   English

如何从Java调用带有标志/开关的Shell脚本

[英]How to invoke a shell script with flags/switches from java

I have a shell script say for eg testDB.sh which takes up credentials(arguments) in the form of switches/flags. 我有一个shell脚本,例如testDB.sh,它以开关/标志的形式占用凭据(参数)。 For eg to execute this script I do the following 例如,要执行此脚本,请执行以下操作

./testDB.sh -u username -p password. ./testDB.sh -u用户名-p密码。

In order to invoke it from java, i follow the traditional methodology. 为了从Java调用它,我遵循传统方法。

Runtime.getRuntime().exec(new String[] {"bash","/<path to test script>/testDB.sh","<username>","<password>"});

The above doesn't seem to help the cause :( 上面似乎没有帮助的原因:(

I would like to know how to invoke this script by passing arguments in the form of flags/switches from java. 我想知道如何通过以Java中标志/开关的形式传递参数来调用此脚本。 How do i pass this -u and -v switches ?? 我如何通过-u和-v开关? Any help would be appreciated 任何帮助,将不胜感激

You need to pass the flags as well: 您还需要传递标志:

new ProcessBuilder("<script path>/testDB.sh",
  "-u", username,
  "-p", password
);

I strongly suggest against any of the other solutions since they are brittle and will fail suddenly when you have spaces somewhere in any of the script's arguments. 我强烈建议不要使用其他任何解决方案,因为它们很脆弱,并且在脚本的任何参数中都留有空格时,它们会突然失败。

如果密码和用户名都存储在变量中,我建议您尝试:

Runtime.getRuntime().exec("<script path>/testDB.sh -u " + username + " -p " + password);

It's not too much of an extension of what you have at the moment. 这不是您目前拥有的扩展。 You currently have... 您目前有...

Runtime.getRuntime().exec(new String[] {"bash","/<path to test script>/testDB.sh","<username>","<password>"});

Update that to 更新到

String command = String.format( "/<path to test script>/testDB.sh -u %s -p %s", username, password );
String[] cmdAndArgs = { "/bin/bash", "-c", command };

Runtime.getRuntime().exec( cmdAndArgs );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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