How can grep interpret literally a string containing an asterisk and is passed to grep through a variable?

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

lies in the fact that it does not work due to an asterisk in the CMD variable. how can i tell grep to see the value of the variable as is? Any solution? It is imperative that grep be passed through a variable. Thanks.

0
source share
3 answers

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

+3
source

The problem is not grep, it is

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

If you do

 echo $CLASSPATH 

You should see that your shell has expanded * all the files in this directory. To fix this, simply use single quotes to prevent freezes:

 CLASSPATH='/blah/libs/*:/blah/more/libs' 
+1
source

Completely unrelated to your specific grep problem, but jps will report the start of Java processes and possibly make your grepping easier, d will most likely have to be simple:

 jps | grep MainClass 

(or something similar)

+1
source

Source: https://habr.com/ru/post/892301/


All Articles