tags:

views:

160

answers:

3

I have this script:

#!/bin/bash
CLASSPATH="/blah/libs/*:/blah/more/libs"
CMD="java -cp $CLASSPATH MainClass"
ALREADY_RUNNING_PID=`ps -ef --no-headers | grep $CMD | grep -v grep | awk '{print $2}'`
if [ "$ALREADY_RUNNING_PID" ]; then
      echo "Already running"
      exit 1
fi
$CMD &

problem is it doesnt work due to the asterisk in the CMD variable. how can i tell grep to see the variable value as it is? Any solution? It is mandatory that grep is fed through the variable. Thanks.

A: 

The problem is not grep, it's

CLASSPATH="/blah/libs/*:/blah/more/libs"

If you do

echo $CLASSPATH

you should see that your shell has expanded the * to all files in that directory. To remedy this, just use single quotes to prevent globbing:

CLASSPATH='/blah/libs/*:/blah/more/libs'
csl
I thought that too, but I added that echo statement before the CMD=... assignement and it is not expanded... i dont know why. Anyway I cant do single quoting because actually CLASSPATH in my real world example consists of other vars:CLASSPATH="$BASEPATH/libs/*:$BASEPATH/morelibs/*"
Paralife
Although maybe i could concatenate, but it seems too ugly to be the only solution
Paralife
+1  A: 

Totally unrelated to your specific grep problem, but jps will report on running Java processes and possibly make your grepping easier since you'd most likely have to just do:

jps | grep MainClass

(or something similar)

Brian Agnew
thanks. very interesting.
Paralife
+3  A: 

Since you are not using regular expressions you can use fgrep $CMD instead of grep

Peter van der Heijden
Solved. Thanks.
Paralife