简体   繁体   中英

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. For eg to execute this script I do the following

./testDB.sh -u username -p password.

In order to invoke it from java, i follow the traditional methodology.

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. How do i pass this -u and -v switches ?? 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 );

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