最近写一个脚本为了获取apache 进程使用CPU的百分比, 本来是如下及脚本
#!/bin/bash cpulist=`ps auxf --width=1000 |grep $1|grep -v grep|awk '{print $3/24}'`; totalCpu=0 for cpu in $cpulist; do let "totalCpu=$totalCpu+cpu" done echo $totalCpu
但是后来服务器的核换成了12个, 所以我就想这个CPU的core数目应该自动获取。就有了如下脚本
#!/bin/ksh coreNumber=`cat /proc/cpuinfo | grep processor | wc -l` cpulist=`ps auxf --width=1000 |grep $1|grep -v grep|awk '{print $3/$cpuNumber}'`; totalCpu=0 for cpu in $cpulist; do let "totalCpu=$totalCpu+cpu" done echo $totalCpu
结果报错:awk: (FILENAME=- FNR=1) fatal: division by zero attempted
查了一会儿,原来awk不允许直接读取shell的变量, 应该使用如下的脚本。
#!/bin/ksh coreNumber=`cat /proc/cpuinfo | grep processor | wc -l` cpulist=`ps auxf --width=1000 |grep $1|grep -v grep|awk -v cpuCores=$cpuNumber '{print $3/cpuCores}'`; totalCpu=0 for cpu in $cpulist; do let "totalCpu=$totalCpu+cpu" done echo $totalCpu
awk -v varName=varValue : 为awk定义各个变量。