简体   繁体   English

BASH传递变量给grep产生不同的结果

[英]BASH pass a variable to grep produce different result

Script: 脚本:

echo $1 $n
while true 
do
  ps -aux | awk '{print $1 "\t" $3 "\t" $4 "\t" $11}'  > task.log
  while IFS=' ' read r
  do 
    echo $r
  done < task.log | grep "$n" | awk '/a/{sum+=$1} END{print"Total CPU Usage:", sum}' >> monitor2.log
  sleep $1
done

This is a simple script to see the cpu usage by output -aux result in task.log and let grep and awk process it sum it all by entering a keyword 这是一个简单的脚本,可在task.log中通过输出-aux结果查看cpu的使用情况,并通过输入关键字让grep和awk处理所有操作的总和

The problem is that the result is always when I run ./monitor1.sh 2 firefox 问题是结果总是在我运行./monitor1.sh 2 firefox时出现

Total CPU Usage: 0 总CPU使用率:0

I tested if I put grep replace $n with firefox and not variable, the output is 我测试了是否将grep用firefox替换$ n而不是变量,输出为

Total CPU Usage: 1.1 总CPU使用率:1.1

In your script: 在您的脚本中:

  • You nowhere assign the variable "$n", thus it is empty. 您无处分配变量“ $ n”,因此它为空。 Probably you mean to use n=$2 or just use $2 positional variable instead 可能您的意思是使用n=$2或仅使用$2位置变量
  • "task.log" is useless, if you want it use tee to pipe to it “ task.log”是无用的,如果您希望使用tee来传送到它
  • Doing ps -axu and then limiting columns with awk looks strange. 进行ps -axu然后用awk限制列看起来很奇怪。 ps can format the output by itself ps可以自己格式化输出
  • Parsing ps | grep 解析ps | grep ps | grep is bad, use pgrep for that ps | grep不好,请使用pgrep
  • remember to quote the variables 记得引用变量

Your script after some fixing may look like this: 修复后的脚本可能如下所示:

while true; do
  cpuusage=$(
      pgrep "$2" | 
      tee >(xargs ps -aux >task.log) | 
      xargs ps -o cpu% |
      awk '{sum += $1} END {print sum}'
  )
  echo "Total CPU Usage: $cpuusage" >> monitor2.log
  sleep "$1"
done
  • pgrep is a better alternative to ps -aux | grep ... pgrep是ps -aux | grep ...的更好替代品ps -aux | grep ... ps -aux | grep ...
  • xargs passes pgrep outupt to ps -o %cpu= xargspgrep outupt传递给ps -o %cpu=
  • ps -o %cpu= prints percent cpu usage for each process ps -o %cpu=显示每个进程的cpu使用百分比
  • awk is used to sum it. awk用于求和。
  • Then a simple echo appends to monitor2.log file. 然后,将简单的回显追加到monitor2.log文件。

I guess you're after something like this: 我想您正在追求这样的事情:

ps aux | awk '$11 ~ /firefox/{ sum += $3 } END { print sum }'

The awk checks field 11 of every row produced by ps and if it contains firefox , it executes the associated {} block. awk检查ps产生的每一行的字段11,如果它包含firefox ,它将执行相关的{}块。 Beware, on different systems the ps outputs are different. 当心,在不同的系统上ps输出是不同的。

You want to run this within a watch command. 您想在watch命令中运行它。 Eg. 例如。 like this (notice how you can avoid quoting hell with the use of awk variables). 这样(注意如何避免使用awk变量引用地狱)。

ps-sum() { ps aux | awk -v regex=$1 '$11 ~ regex { sum += $3 } END { print sum }' ;}
export -f ps-sum

watch -x bash -c "ps-sum firefox"

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

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