简体   繁体   English

将 jps -vl 命令的输出分配给 shell 脚本中的变量

[英]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.当我像上面那样尝试时,grepped 的所有 java 进程都在一行中分配给 JAVA_PROCESSES 变量。 Processes are not separated by new line.进程不以换行分隔。 Therefore $NUMBER_OF_JAVA_PROCESSES always give 1 for me.因此 $NUMBER_OF_JAVA_PROCESSES 总是给我 1。

Also $NUMBER_OF_JAVA_PROCESSES show 1 even no processes are assigned to JAVA_PROCESSES due to the empty line in $JAVA_PROCESSES.由于 $JAVA_PROCESSES 中的空行,即使没有进程分配给 JAVA_PROCESSES,$NUMBER_OF_JAVA_PROCESSES 也会显示 1。

Please suggest a way to assign grepped processes separated by new line.请建议一种分配由新行分隔的 grepped 进程的方法。

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:此外,我们可以通过使用扩展的正则表达式并只需要一个进程来简化grep

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:假设jps输出的所有行都不能包含换行符,如果需要,我们可以在此之后获得计数:

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.你遇到的主要问题是你没有引用你的变量,所以echo $JAVA_PROCESSES被扩展然后受到分词,所以你的换行符被外壳“吃掉”。 You'd always have only one line which would be a space separated list of all the words in your JAVA_PROCESSES variable.您总是只有一行,它是JAVA_PROCESSES变量中所有单词的空格分隔列表。 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). echo也总是会在最后添加一个换行符,这有时很好,有时不太好,但您应该意识到它正在发生(这就是为什么即使没有进程,您也总是会得到 1 的计数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM