[英]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: 在您的脚本中:
n=$2
or just use $2
positional variable instead n=$2
或仅使用$2
位置变量 tee
to pipe to it tee
来传送到它 ps -axu
and then limiting columns with awk
looks strange. ps -axu
然后用awk
限制列看起来很奇怪。 ps
can format the output by itself ps
可以自己格式化输出 ps | grep
ps | grep
ps | grep
is bad, use pgrep
for that ps | grep
不好,请使用pgrep
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
ps -aux | grep ...
ps -aux | grep ...
的更好替代品ps -aux | grep ...
ps -aux | grep ...
xargs
passes pgrep
outupt to ps -o %cpu=
xargs
将pgrep
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
用于求和。 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.