Use ps, grep, cut, awk and tr to list running Java processes - huwenyuan/Linux GitHub Wiki

Use ps aux | grep java can list all running processes. But the output contains a lot of Java command options that will make the output difficult to find useful information. Like:

root 3189 0.3 9.2 352904 95436 ? Sl 19:18 0:46 /usr/java/latest/bin/java -server -cp /usr/MessageQueue/mq/bin/../lib/imqbroker.jar:/usr/MessageQueue/mq/bin/../lib/imqutil.jar:/usr/MessageQueue/mq/bin/../lib/jsse.jar:/usr/MessageQueue/mq/bin/../lib/jnet.jar:/usr/MessageQueue/mq/bin/../lib/jcert.jar:/usr/lib/audit/Audit.jar:/opt/sun/mfwk/share/lib/jdmkrt.jar:/opt/sun/mfwk/share/lib/mfwk_instrum_tk.jar:/usr/MessageQueue/mq/bin/../lib/ext:/usr/MessageQueue/mq/bin/../lib/ext -Xms192m -Xmx192m -Xss192k -XX:MaxGCPauseMillis=5000 -Dimq.home=/usr/MessageQueue/mq/bin/.. -Dimq.varhome=/usr/MessageQueue/mq/bin/../../var/mq -Dimq.etchome=/usr/MessageQueue/mq/bin/../../etc/mq -Dimq.libhome=/usr/MessageQueue/mq/bin/../lib com.sun.messaging.jmq.jmsserver.Broker -reset messages -Dimq.hostname=0.0.0.0 -Dimq.jms.max_threads=2000

To make the output more readable, we want to just show user, PID, java command, the main class etc. To accomplish this, first uses cut command to remove %CPU, %MEM, VSZ, RSS, TTY, TIME etc. like this:

ps aux | grep java | grep -v grep | cut -b 1-15,66-2000

Next, uses awk command to remove options which is start with "-". Also need to remove classpath which normally contains ":". The ask command is like this:

awk '{for (i=1;i<NF;i++) printf("%s %s",$(i) !~ /^-|:/ ? $(i):"", i==NF ? "\n":"")}'

Now the result is much better:

nms 2844 java         com.mwi.mininms.dispatcher.NmsDispatcher
nms 2863 java     com.mwi.snmpreceiver.Main conf/snmpReceiver/snmpReceiver.conf
root 3189 /usr/java/latest/bin/java            com.sun.messaging.jmq.jmsserver.Broker  messages
root 3354 java  /opt/symmetric-ds/lib/symmetric-wrapper.jar exec /opt/symmetric-ds/conf/sym_service.conf
root 3365 java                     org.jumpmind.symmetric.SymmetricLauncher  8080

But it contains a lot of extra spaces. To remove them use tr command. The complete command is like this:

ps aux | grep java | grep -v bash | grep -v grep | cut -b 1-15,66-2000 | awk '{for (i=1;i<=NF;i++) printf("%s %s",$(i) !~ /^-|:/ ? $(i):"", i==NF ? "\n":"")}' | tr -s "[:blank:]"

The output is this:

nms 2844 java com.mwi.mininms.dispatcher.NmsDispatcher 
nms 2863 java com.mwi.snmpreceiver.Main conf/snmpReceiver/snmpReceiver.conf 
root 3189 /usr/java/latest/bin/java com.sun.messaging.jmq.jmsserver.Broker messages 
root 3354 java /opt/symmetric-ds/lib/symmetric-wrapper.jar exec /opt/symmetric-ds/conf/sym_service.conf 
root 3365 java org.jumpmind.symmetric.SymmetricLauncher 8080