脚本内容如下:
#!/bin/sh
mem=`free -m | awk 'NR==2{print $2}'`
ps -aux 2>&1 | sort -k 4 -r | awk '$4 ~ /^[0-9]/ && $4>0 {print $4,$11}' | awk '{print $1/100*mem" "$2}' mem=$mem | sort -k 2 | awk '
{
a[$2] += $1;
b[$2]++;
total += $1;
total++;
}
END{
for(i in a){
t=i;
gsub(/:|.*\//, "", t);
printf "%10s %s\n" ,a[i]"MB", t"["b[i]"]";
}
print "Memory Total: "mem"MB, used: "total"MB, free: "mem-total"MB."
}' mem=$mem | sort -n -r
执行结果:
root@postgresql:~# sh cpu.sh
118.53MB mysqld[1]
67.167MB apache2[6]
23.706MB postgres[1]
11.853MB snapd[1]
7.902MB systemd-journald[1]
7.902MB sshd[2]
3.951MB systemd-udevd[1]
3.951MB systemd[1]
3.951MB sshd[1]
3.951MB postgres[1]
3.951MB polkitd[1]
3.951MB init[1]
3.951MB -bash[1]
3.951MB accounts-daemon[1]
Memory Total: 3951MB, used: 288.668MB, free: 3662.33MB.