简体   繁体   中英

How to pass a string variable as a shell script argument?

I have string variables as

String var1 = "I am"
String var2 = "here"
String cmd = ("sh /path/shell.sh \""+var1+"\" \""+var2);
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);

But when I execute echo $1 $2 from my shell script, I get the output as I am . Why doesn't the quotes work?

You'll want to call the command as follows:

Process process = new ProcessBuilder().command("sh", "/path/shell.sh", var1, var2);
Scanner scan = new Scanner(process.getInputStream());
while(scan.hasNextLine()) {
    //...
}
//...
scan.close();
process.destroy();

You'll probably want to wrap that in a try-catch block too.

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