Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'm running Ubuntu 11 and I'm having some issues with grep.

I have a shell script (see below) which essentially checks if a certain Java program of mine is running, if not it runs it. That part works out great!

If my Java application throws any kind of exception however I would like to capture that information and email it to myself. How can I go about checking to see if the call to java -jar /bin/MyApp.jar fails? I tried piping it to grep, but that doesn't seem to work.

Below is the full script that I've written:

#Check if MyApp.jar is running, if not run it.
if [ $(ps aux | grep 'java' | grep -v grep | wc -l | tr -s "\n") -eq 0 ]
then
echo "PacketCapture Starting...\n"
java -jar /bin/MyApp.jar
echo "PacketCapture Started.\n"
else
echo "PacketCapture already running.\n"
fi
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

You have to redirect the output of stderror stream to stdout stream since exceptions are logged in stderr stream. The below snippet can filter the exception strace and prints upto 10 following lines.

$ java -jar /bin/MyApp.jar 2>&1 | grep "^Exception" -A10

Note: You can use jps command to find the java process for sun JVM. You can also try pidof or pgrep commands or grep '[j]ava'(this one will not list its(grep) process) too.

share|improve this answer
    
This works! Much thanks. Can you however explain 2>&1 does or direct me to some reading on it? I'd hate to just use this and have no idea what it's really doing –  BOMEz Jun 20 '12 at 18:59
1  
@BOMEz, try this one wiki.bash-hackers.org/howto/redirection_tutorial –  geirha Jun 21 '12 at 0:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.