好久沒寫指令碼了,都開始忘記了,今天嘗試著寫了下,好多東西都要現查了,以後會每天寫點,簡單或者難的,有技術的沒技術的,總之,這東西多練習才好。
今天寫的這個指令碼先放這,一點點完善.
#!/usr/bin/env bash
PROC_FILE="/proc/stat"
function getline {
#Original data, it looks like "cpu 391560 66418 112967 3144467 53328 10123 1642 0 0"
local data=`cat $PROC_FILE | head -n 1`
CUSER=`echo $data | awk '{print $2}'`
CNICE=`echo $data | awk '{print $3}'`
CSYSM=`echo $data | awk '{print $4}'`
CIDLE=`echo $data | awk '{print $5}'`
CIOW=`echo $data | awk '{print $6}'`
CIRQ=`echo $data | awk '{print $7}'`
CSIRQE=`echo $data | awk '{print $8}'`
CSTEAL=`echo $data | awk '{print $9}'`
CGUEST=`echo $data | awk '{print $10}'`
CSUM=`expr $CUSER + $CNICE + $CSYSM + $CIDLE + $CIOW + $CIRQ + $CSIRQE + $SCTEAL + $CGUEST`
}
function calculate {
#This is the sleep time between each getline invoke
local delay=1
if [ -n "$1" ] ; then
delay=$1
fi
getline
C_USER=$CUSER
C_NICE=$CNICE
C_SYSM=$CSYSM
C_IDLE=$CIDLE
C_SUM=$CSUM
sleep $delay
getline
DIFF=`expr $CSUM - $C_SUM`
U_USER=`echo "( $CUSER - $C_USER ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`
U_NICE=`echo "( $CNICE - $C_NICE ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`
U_SYSM=`echo "( $CSYSM - $C_SYSM ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`
U_IDLE=`echo "( $CIDLE - $C_IDLE ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`
C_USER=$CUSER
C_NICE=$CNICE
C_SYSM=$CSYSM
C_IDLE=$CIDLE
C_SUM=$CSUM
}
function stat {
local REPEAT=1
local DELAY=1
if [ -n "$1" ]; then
REPEAT=$1
fi
if [ -n "$2" ]; then
DELAY=$2
fi
echo
echo "---CPU usage statistic---"
echo "User% Nice% System% Idle%"
for (( i=1; i<=$REPEAT; i++ )); do
calculate $DELAY
echo "${U_USER}% ${U_NICE}% ${U_SYSM}% ${U_IDLE}%"
done
echo "-------End------"
}
function help {
cat <<-EOF
Usage: $0 -h or $0 repeat_num delay_time
EOF
}
### Main part of this script ###
stat $1 $2
exit 0