"Ayesha Ahsan" <ay****@ou.ed u> wrote in message
news:13******** *************** ***@posting.goo gle.com...
Hi,
I use Runtime.getRunt ime().exec(comm and) to make my
system call. For Windows based Dos, i add "cmd /c"
before I type in my system call. So for example make
the system call "dir":
String command="cmd /c dir";
Runtime.getRunt ime().exec(comm and);
What is the equivalent of cmd /c in Unix .
Since you cross-posted to UNIX NG's I'm sure you received fairly in-depth
responses to your query. Still, it might be worth mentioning that *NIX /
Linux systems actually have several, fairly standard, command interpreters
[or 'shells', as they are commonly called] rather than the single one found
on Windows-family systems.
The default shell, which is, on Linux systems in particular, a Bourne Shell
derivative like 'bash', is commonly aliased as 'sh', and, as has been
mentioned, is invoked via:
sh -c
From a Java usage standpoint it is worth bearing in mind that:
* Invoking a shell creates another process, hence any output will
not appear on your Java console. It must, instead, be redirected
to external files, or be captured by your program [see below]
* Passing arguments to shells can be quite error prone, particularly
if parts of command strings are not properly 'escaped'. Also,
it seems safest to pass arguments to *NIX / Linux shells via
a 'String[]' rather than a single 'String'
I hope this helps.
Anthony Borla
// =============== =============== =====
import java.io.FileInp utStream;
import java.io.InputSt reamReader;
import java.io.Buffere dReader;
import java.io.IOExcep tion;
public class ShellCommands
{
public static void main(String[] args)
{
System.out.prin t(executeShell( "sh", "-c", "ls", "*.xxx", retCode)
+ " : " + retCode[0]);
}
private static String executeShell(St ring shell, String shellOpts,
String cmd, String cmdArgs, int[] retCode)
{
String[] cmdString = { shell, shellOpts, cmd, cmdArgs };
String commandOutput = null;
try
{
Process p = Runtime.getRunt ime().exec(cmdS tring);
BufferedReader pOutput =
new BufferedReader(
new InputStreamRead er(p.getInputSt ream()));
String line;
StringBuffer tmpCommandOutpu t = new StringBuffer();
try
{
while ((line = pOutput.readLin e()) != null)
tmpCommandOutpu t.append(line). append("\n");
commandOutput = tmpCommandOutpu t.toString();
}
catch (IOException e) {}
p.waitFor(); retCode[0] = p.exitValue(); pOutput.close() ;
}
catch (IOException e) {}
catch (InterruptedExc eption e) {}
return commandOutput;
}
}