This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Running UNIX command from Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Running UNIX command from Java" Watch "Running UNIX command from Java" New topic

Running UNIX command from Java

Donny Wi

Joined: Jan 24, 2002
Posts: 13
I'm having problem running the UNIX "grep" command from java.
This is what my code looks like:

When I ran the "grep" command above, it return exit code=1, which means no match found.
When I replace the "grep" command with "ls", it works fine. When I replace the "grep" command with "wc -l", first it returns zero but when I added a empty loop to delay the parent program, I got the right value.
I use waitFor() method, but I think it does not work well.
Can someone please help me or tell my why "grep" command does not work from Java?

Donny Widjaja
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

Ya, I get the same problem.
Donny Wi

Joined: Jan 24, 2002
Posts: 13
I found the answer but I can't explain why:
Instead of using
1. Runtime.getRuntime().exec(sCommand);
I use
2. Runtime.getRuntime().exec(new String[] {"/usr/bin/sh", "-c", sCommand});
I saw some example that runs multiple command by using code number 2, so I just experiment with the code and suddently the process.waitFor() will actually wait until the sub-process is complete. I don't know why.
So, there was my 10 hours of experiment with Runtime class in Java.
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
Just think how many OTHER people will not have to waste 10 hours discovering that - just because of YOU.
You should be pleased with yourself . WE are .
I agree. Here's the link:
subject: Running UNIX command from Java
It's not a secret anymore!