I was goofing around and decided I'd write a quick script that calls
ifconfig so as to determine how much bandwidth is being used (up and down
stream) on average. I wound up with something that I think would work, but
I'm wondering if I can't do it better. As it stands, I call grep and cut a
lot. I got to thinking though that awk might save me some of that
(admittedly negligible) overhead. If I could pipe the ifconfig output
through awk, that would, I'd think, run ever so slightly faster. However, I
can't figure awk out. I don't actually have access to awk here, but this is
something that I'm doing to keep my mind sharp. I'm hoping someone can help
me out. Since there's a chance a friend of mine might wind up using
something like this very script, I want to get it as fast AND as accurate
as I can. I've copied the script as I THINK it should be below. If someone
knows awk, please check it for me. And if you guys know a good web tutorial
on awk, I'd love to know of it. Also, if there's a better way to do the
math than using bc (since I don't think bash's math functions support
decimals) I'd be curious to know of it. And yes, I know I could likely do
something like this in perl with less work, but I know less about perl than
I do about awk, so that's out of the question for now. Besides, this script
may run on machines that don't HAVE perl. Thanks!
--- Dan
#!/bin/bash
# actual line in question looks like: RX bytes:1024 (1 KiB) TX bytes:4096
(4 KiB)
read START_RX START_TX <<< $(ifconfig eth0 | awk -F'[[:space:]:]+' '/bytes/
{$print $3 $8}')
sleep 5
read NEW_RX NEW_TX <<< $(ifconfig eth0 | awk -F'[[:space:]:]+' '/bytes/
{print $3 $8}')
read AVG_RX AVG_TX <<< $(echo -e "($NEW_RX - $START_RX) * 8 / 5 / 1024 /
1024" \n($NEW_TX - $START_TX) * 8 / 5 / 1024 / 1024" | bc)
echo -e "Average Megabits transmitted: $AVG_TX\t\t received: $AVG_RX"
/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/