0

I'm trying to execute unix commands thru a java program. Some of these commands involve an if-then-fi statement. Can this be done thru java / Runtime class? Seems like it only handles 1 command at a time. I'm looking to do something like this:

grep 'Error One'   SystemErr.log > $HOME/tempFiles/output.txt
grep 'Error Two'   SystemErr.log >> $HOME/tempFiles/output.txt
grep 'Error Three' SystemErr.log >> $HOME/tempFiles/output.txt
.
.

if [ -s $HOME/tempFiles/output.txt ]
then
    mail -s "Subject here" "[email protected]" < $HOME/tempFiles/output.txt
fi

Basically, I just want to email the file (results) if the grep found anything. I want to use java instead of a direct shell script so that the errors I search for can be database-driven, easier to change.

I know I could read the file myself in java and search/parse it myself. But grep and other unix commands have a lot of built-in functionality I want to use to make it easier.

Any ideas, or am I totally on the wrong track?

2
  • You're conflating bash with the ability to execute a command. Java isn't using a shell when you use the Runtime class. You'll need to programmatically write a bash script and launch it with the bash executable. Commented Jul 28, 2014 at 18:55
  • 1
    If you are keen on using shell script, the best option is to probably write a script which can take the error messages to search for as parameter. Commented Jul 28, 2014 at 19:06

1 Answer 1

1

Here is some code, using simpler commands, but basically equivalent:

public static void main( String[] args ) throws Exception {
    try { 
        ProcessBuilder pb = new ProcessBuilder( "/bin/bash", "-c",
                   "echo one >/tmp/xxx && echo two >>/tmp/xxx && " +
                   "if [ -s /tmp/xxx ]; then cp /tmp/xxx /tmp/yyy; fi" );
        File log = new File( "/tmp/log.txt" );
        pb.redirectOutput(ProcessBuilder.Redirect.appendTo(log));
        Process process = pb.start();
        process.waitFor();
    } catch( Exception e ){
        // ...
    } catch( Error e ){
        // ...
    }
}

The trick is to put it all into a single shell command so that you can call /bin/bash with the -c command option.

If composing this command is too complicated, write a shell file and source that.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! I had tried this, but think I missed the syntax of the ';' after the IF and then THEN statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.