Monitoring real-time network traffic is a common requirement in Linux system administration and DevOps operations. This article presents a lightweight Bash script that tracks incoming (RX) and outgoing (TX) traffic on a specified network interface by reading kernel statistics from /proc/net/dev.
The script calculates per-second bandwidth usage and automatically converts raw byte counts into human-readable units for clarity.
📡 Real-Time Network Traffic Monitoring Script #
The script continuously samples network interface counters once per second and displays live throughput statistics.
#!/bin/bash
# Set interface name (e.g., eno1, eth0, wlan0)
eth="eno1"
# Convert bytes to human-readable units
bytes_to_human() {
local bytes=$1
if (( bytes < 1024 )); then
echo "${bytes}B"
elif (( bytes < 1048576 )); then
printf "%.2fKB" "$(bc <<< "scale=2; $bytes / 1024")"
elif (( bytes < 1073741824 )); then
printf "%.2fMB" "$(bc <<< "scale=2; $bytes / 1048576")"
else
printf "%.2fGB" "$(bc <<< "scale=2; $bytes / 1073741824")"
fi
}
# Real-time monitoring loop
while true; do
RXpre=$(grep "$eth:" /proc/net/dev | awk '{print $2}')
TXpre=$(grep "$eth:" /proc/net/dev | awk '{print $10}')
sleep 1
RXnext=$(grep "$eth:" /proc/net/dev | awk '{print $2}')
TXnext=$(grep "$eth:" /proc/net/dev | awk '{print $10}')
RX=$((RXnext - RXpre))
TX=$((TXnext - TXpre))
RX_human=$(bytes_to_human $RX)
TX_human=$(bytes_to_human $TX)
clear
echo -e "\t RX `date +%H:%M:%S` TX"
echo -e "$eth \t $RX_human/s $TX_human/s"
done
⚙️ Script Functionality Overview #
This script provides a live, terminal-based dashboard for network throughput on a single interface, making it useful for diagnostics, performance analysis, and troubleshooting.
Key characteristics include:
- Per-second refresh rate for real-time visibility
- Automatic unit scaling from bytes to KB, MB, or GB
- Minimal dependencies, using standard Linux tools and
/proc
🧠 How It Works Internally #
-
Interface Selection The
ethvariable defines the network interface to monitor (for example,eno1,eth0, orwlan0). -
Kernel Statistics Access Linux exposes cumulative network counters through
/proc/net/dev, which tracks RX and TX bytes since system boot. -
Rate Calculation The script samples counters, waits exactly one second, then samples again. The difference between samples represents bytes per second.
-
Human-Readable Formatting Since Bash lacks floating-point arithmetic, the
bcutility is used to format bandwidth values accurately.
🚀 How to Use the Script #
- Create the script file
nano monitor_traffic.sh
- Paste the script
Ensure the
ethvariable matches your network interface. You can list interfaces with:
ip link
- Make it executable
chmod +x monitor_traffic.sh
- Run
./monitor_traffic.sh
- Exit Press Ctrl+C to stop monitoring.
This approach offers a transparent and efficient alternative to heavier monitoring tools, making it ideal for quick diagnostics, embedded systems, or minimal server environments.