Pat O
Pat O

Reputation: 3

shell script if statement executed from java?

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?

Upvotes: 0

Views: 789

Answers (1)

laune
laune

Reputation: 31290

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.

Upvotes: 1

Related Questions