I'm having difficulty executing a batch file in Java that expects parameters. These parameters may contain spaces so I need to wrap them in quotes. I will also need to do the same thing for Linux because some of the parameters may contain special characters such as !
.
Non-functional Windows code:
ProcessBuilder pb = new ProcessBuilder(
"cmd",
"/c",
"\"mybat.bat\"",
"\"param 1\"",
"\"param 2\"",
"\"param 3\""
);
Non-functional Linux code:
ProcessBuilder pb = new ProcessBuilder(
"bash",
"-c",
"'myshellscript.sh'",
"'param 1'",
"'param 2'",
"'param 3'"
);
I understand that I should be adding the parameters like the Windows example below, but this won't work with the spaces:
ProcessBuilder pb = new ProcessBuilder(
"cmd",
"/c",
"mybat.bat param 1 param 2 param 3"
);
How should this be done?
Expand the database that you want, expand Programmability, and then expand Stored Procedures. Right-click the user-defined stored procedure that you want and select Execute Stored Procedure. In the Execute Procedure dialog box, specify a value for each parameter and whether it should pass a null value.
In computing, a procedural parameter is a parameter of a procedure that is itself a procedure.
Parameters are used to exchange data between stored procedures and functions and the application or tool that called the stored procedure or function: Input parameters allow the caller to pass a data value to the stored procedure or function.
Windows:
ProcessBuilder pb = new ProcessBuilder(
"cmd", "/c", "mybat.bat",
"param 1", "param 2", "param 3");
Unix:
ProcessBuilder pb = new ProcessBuilder(
"sh", "mybat.sh",
"param 1", "param 2", "param 3");
No, you should not quote the args on *nix. Quoting is necessary on *nix in an interactive shell to prevent the shell misinterpreting them, but when launching a process directly a shell isn't involved. Hence no need to quote.
If you do include the quotes, the launched process will see them as part of its incoming arguments and do things like (for example) try to open filenames containing quotes.
You also do not want the "-c" argument to bash. That tells it to parse the next argument as a command line, but you're supplying a list of arguments. Remove the "-c" option and the excess quotes and it should work.
The proper Linux call would be:
ProcessBuilder pb = new ProcessBuilder(
"bash",
"myshellscript.sh",
"param 1",
"param 2",
"param 3"
);
Also not that if the file "myshellscript.sh" is executable and has the appropriate shebang line (e.g. "#!/bin/bash"), you do not need the "bash" argument either. This is preferrable because if the script is ever replaced with one written in a different language you won't have to update your calling app.
Likewise, on Windows, you shouldn't need the "cmd" and "/c" arguments. The process launcher / OS should handle launching the batch file (based on extension) automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With