Ricky Ricky - 3 years ago 98
Bash Question

Assign a output of jps -vl command to a variable in shell script

I need to assign the output of a command to a variable. The command I tried is:

#!/bin/bash
JAVA_PROCESSES=`jps -vl | grep -v 'sun.tools.jps.Jps' | grep -v 'hudson.remoting.jnlp.Main' | grep -v grep`
NUMBER_OF_JAVA_PROCESSES=`echo $JAVA_PROCESSES | wc -l`
echo $NUMBER_OF_JAVA_PROCESSES
echo $JAVA_PROCESSES
..


When I tried as in above, all java processes grepped are assigned to JAVA_PROCESSES variable in one line. Processes are not separated by new line. Therefore $NUMBER_OF_JAVA_PROCESSES always give 1 for me.

Also $NUMBER_OF_JAVA_PROCESSES show 1 even no processes are assigned to JAVA_PROCESSES due to the empty line in $JAVA_PROCESSES.

Please suggest a way to assign grepped processes separated by new line.

Answer Source

If the main thing you want is to know whether or not you got any at all, you could just test if the variable is empty:

java_procs=$(jps -vl | grep -v 'sun.tools.jps.Jps' | grep -v 'hudson.remoting.jnlp.Main' | grep -v grep)
if [ -z "$java_procs" ]; then
    echo "No processes"
fi

Also, we can simplify the grep by using extended regex and just needing a single processes:

java_procs=$(jps -vl | grep -Ev 'sun.tools.jps.Jps|hudson.remoting.jnlp.Main|grep')

Assuming none of the lines output by jps can contain linebreaks themselves, we could get the count after that if we need it:

num_procs=$(printf '%s\n' "$java_procs" | wc -l)

The main problem you were running into is that you weren't quoting your variable, so echo $JAVA_PROCESSES was being expanded and then subject to word splitting, so your newlines were being "eaten" by the shell. You'd always have only one line which would be a space separated list of all the words in your JAVA_PROCESSES variable. To protect from word splitting you can quote the variable, as I did in my code above.

echo will also always add a line break at the end, which is good sometimes, and not so good sometimes, but you should be aware of it happening (that's why you would always get a count of 1 even when there were no processes).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download