This answer is similar to your other question. Once again, vmstat(8)
will be our friend.
Example output:
$ vmstat 1 2
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
0 0 752 135436 31276 392252 0 0 2 1 40 101 0 0 99 0
0 0 752 138404 31396 392816 0 0 0 0 68 188 1 1 98 0
The first line is the average since reboot, the second line is a sampling of the last second.
From the manpage:
System
in: The number of interrupts per second, including the clock.
cs: The number of context switches per second.
We can use awk(1)
to parse the output:
ints=$(vmstat 1 2 | tail -1 | awk '{print $11}')
This should work on Linux, FreeBSD, and probably MacOSX.