I haven't written the script for a long time, and I forgot it. I tried to write it today. I have to check many things. I will write something simple or difficult every day, there are no technical skills. In short, it is good to practice more.
The script I wrote today should be put here first, which is a little bit more complete.
#! /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 }/. [0-9] {1, 2 }"'
U_nice = 'echo "($ cnice-$ c_nice)/$ diff * 100" | BC-L | grep-e-o "[0-9 }/. [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