Shell – Extract tomcat parameters from ps output

psshell-scripttext processing

I'm trying to write a little diagnostic tool and one of the functions I want from it is that I want to run is:

ps axu | grep tomcat | grep -v grep | awk '{ print $<list of desired fields> }'  

I want to return the userid that started tomcat and the following parameters that were passed when tomcat started:

-javaagent:/usr/share/tomcat7/<someagent> -Dcatalina.base=/var/lib/tomcat7 
- Dcatalina.home=/usr/share/tomcat7 -Djava.io.tmpdir=/tmp/tomcat7-tomcat7-tmp

I want those fields passed into an array which I can then use to tell the user something about the tomcat install.

The problem is I can't find a way of formatting the command to force the fields to be what I need them to be to make awk work.

At this point I'm thinking of just taking the output, writing it to a temp file, then pulling what I want out using regex.

I know there's a way to do this in Bash but I have not had any success getting there from here.

Best Answer

Pass the -o option to ps to control which fields it outputs. If you add an = sign after all the fields, then the header line is omitted.

Use -e instead of ax to stick to standard features (this will work on any non-antique unix).

Your filter with grep is not robust. For example, if you run this command from a script called look-for-tomcat, then your script would be matched as well. Here's a more robust way that looks for a JVM process with org.apache.catalina.startup.Bootstrap as an argument.

ps -e -o user=,args= | awk '
    $2 ~ /java$/ &&  / org\.apache\.catalina\.startup\.Bootstrap($| ) {
        print "user name: ", $1;
        if (match($0, / -javaagent:[^ ]* /)) print substr($0, RSTART+1, RSTART+RLENGTH-2);
        # etc.
    }'

Even better would be to log the PID of the tomcat process in a file (e.g. /var/run/tomcat.pid) when it starts.

Related Question