Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ]
echo "PacketCapture Starting...\n"
java -jar /bin/MyApp.jar
echo "PacketCapture Started.\n"
echo "PacketCapture already running.\n"
share|improve this question
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
@BOMEz, try this one – geirha Jun 21 '12 at 0:13

Your Answer


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.