0

I have this line inside my shell script:

tomcatPID=$(ps -ef | grep tomcat | grep $TOMCAT_ACCOUNT | grep -v grep | grep -v restart | awk '{print $2}')

I made sure that the $TOMCAT_ACCOUNT part is okay. What I have problems with is the grep -v. That works in the terminal, but when I put it in the shell script, it ignores that grep and gives me results that include it.

The question is: Why is grep -v being ignored inside a shell script but on the terminal it works fine?

For example:

Let's say I'm working under become application, so am at application@servername and in the terminal I run:

tomcatPID=$(ps -ef | grep tomcat | grep application | grep -v grep | grep -v restart | awk '{print $2}')

Output: 42345 which only the processID for the tomcat that is running my application.

If I create file.sh and inside I have the exact same:

tomcatPID=$(ps -ef | grep tomcat | grep $TOMCAT_ACCOUNT | grep -v grep | grep -v restart | awk '{print $2}')

and then run it using: ./file.sh output: 42345 6534 which are the processID of my tomcat and the processID of the grep that I'm running. Hence, the grep -v grep to avoid getting that second processID but it gets ignored inside the .sh file.

12
  • 2
    Could you use tomcatPID=$(pgrep tomcat) instead. Read man pgrep.
    – waltinator
    Commented Jun 9, 2021 at 23:03
  • 1
    the question is: Why is grep -v being ignored inside a shell script but on the terminal it works fine??
    – Lipaw11
    Commented Jun 9, 2021 at 23:03
  • 4
    @Lipaw11 to help answer that, I suggest you remove the | awk '{print $2}' and then add echo "$tomcatPID" so we can see exactly what it is matching Commented Jun 9, 2021 at 23:14
  • 2
    tomcatPID=$(ps -fu "$TOMCAT_USER" | awk '/[t]omcat/ && !/[r]estart/ {print $2}') maybe Commented Jun 9, 2021 at 23:42
  • 1
    Please edit the question to show the most simple case you can create of a command and its output that supports your claim.
    – Jim L.
    Commented Jun 10, 2021 at 6:56

1 Answer 1

2

Suggesting a better way to get the PID that you want, use pgrep. This example will find my java tomcat process

TOMCAT_ACCOUNT=tomcat
ps -fu "$TOMCAT_ACCOUNT"
UID        PID  PPID  C STIME TTY          TIME CMD
tomcat     678     1  0 Jun04 ?        00:47:49 /usr/lib/jvm/java-11-openjdk-amd64/bin/java -Dja
tomcat    1900   678  0 Jun04 ?        00:00:02 /usr/lib/libreoffice/program/soffice.bin --accep

pgrep -u "$TOMCAT_ACCOUNT" java
678

If you've got very particular requirements (it must have tomcat in a process command being run by the $_TOMCAT_ACCOUNT user and must not contain restart anywhere in the line) you could use this

TOMCAT_ACCOUNT=tomcat
ps -fu "$TOMCAT_ACCOUNT" | awk '/.[t]omcat/ && !/[r]estart/ {print $2}'
678
1
  • Thank you Roaima!!!! The second solution is exactly what I needed!!! :)
    – Lipaw11
    Commented Jun 11, 2021 at 15:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .