/proc/net/dev to calculate byte deltas over a time interval. By reading the receive and transmit columns for your specific interface, subtracting previous values, and dividing by the elapsed seconds, you derive accurate bits per second metrics. This approach avoids external dependencies like vnstat and provides real-time data directly from the kernel.
Understanding /proc/net/dev Data Structure
The primary source for network statistics on Linux systems is the virtual file/proc/net/dev. This file contains a header followed by lines for each network interface. Understanding the column layout is critical because many scripts fail due to incorrect index assumptions. The structure typically looks like this:
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo: 10 1 0 0 0 0 0 0 10 1 0 0 0 0 0 0
eth0: 500000 4000 0 0 0 0 0 0 100000 1000 0 0 0 0 0 0
The key insight is that the "Receive" section starts at column 2 (index 1 if zero-based) and the "Transmit" section starts at column 18 (index 17 if zero-based). Specifically, the total bytes received are in the first number after the interface name, and total bytes transmitted are in the first number of the transmit block. If you assume different indices, such as treating TX as column 2, your script will output garbage data or crash. Always verify these positions against your system's output, as they are standard across modern Linux kernels but can vary on obscure embedded systems.
For more details on securing your scripts while handling sensitive system data, see How to Improve Bash Performance and Secure Passwords.
Calculating Speed with Delta Time
Network speed is not a static value stored in the system; it is a rate of change. To get the current speed, you need two snapshots of the cumulative byte counters taken at slightly different times. The formula is straightforward:Speed = (Current_Bytes - Previous_Bytes) / Time_Difference
This calculation gives you bytes per second. To convert to bits per second (bps), which is the standard unit for network speed, multiply the result by 8. You should perform this calculation separately for both RX (receive) and TX (transmit) channels.
Here is a robust bash function that implements this logic. It uses awk for efficient parsing and arithmetic.
#!/bin/bash
get_net_speed() {
local iface="${1:-eth0}"
local interval="${2:-1}" # Seconds between samples
# Function to read current bytes
read_bytes() {
# Extract RX bytes (col 2) and TX bytes (col 18)
awk -v iface="$iface" '$1 ~ iface":" {print $2, $10}' /proc/net/dev
}
# First sample
read current_rx_tx <<< $(read_bytes)
current_rx=$(echo "$current_rx_tx" | cut -d' ' -f1)
current_tx=$(echo "$current_rx_tx" | cut -d' ' -f2)
# Wait for the interval
sleep "$interval"
# Second sample
read prev_rx_tx <<< $(read_bytes)
prev_rx=$(echo "$prev_rx_tx" | cut -d' ' -f1)
prev_tx=$(echo "$prev_rx_tx" | cut -d' ' -f2)
# Calculate differences
rx_diff=$((current_rx - prev_rx))
tx_diff=$((current_tx - prev_tx))
# Convert to bits per second
rx_bps=$((rx_diff * 8 / interval))
tx_bps=$((tx_diff * 8 / interval))
echo "RX: ${rx_bps} bps | TX: ${tx_bps} bps"
}
# Usage example
get_net_speed "eth0" 1
Notice how we use $2 for RX and $10 for TX in the awk command. In awk, fields are 1-indexed. Column 1 is the interface name (e.g., eth0:). Column 2 is the RX bytes. Counting across the whitespace-separated fields, the TX bytes fall into field 10. This matches the visual layout where there are 8 fields in the receive block (including the interface label in some views, but strictly speaking, the stats start at col 2) and the transmit block starts later. Wait, let us be precise. In the raw /proc/net/dev text:
Field 1: Interface Name (eth0:)
Field 2: RX Bytes
...
Field 9: RX Multicast
Field 10: TX Bytes
Yes, field 10 is correct for TX bytes in the standard /proc/net/dev format. Using $18 would be incorrect unless you were counting every single whitespace including empty ones, which awk does not do by default. Stick to $2 and $10.
Handling Interface Names and Permissions
Not all systems useeth0. Modern systems often use predictable naming schemes like enp0s3 or wlan0. Your script should allow the user to specify the interface dynamically. Additionally, reading /proc/net/dev is generally permitted for all users, so root privileges are not required for monitoring. However, if you intend to write this speed data to a log file located in a protected directory, you may need elevated permissions. For guidance on writing debug data to root-owned files safely, refer to How to Write Debug Data to a Root Owned File in Bash.
Always validate that the interface exists before parsing. You can check for the interface using ip link show or by grepping /proc/net/dev for the string. If the interface is not found, the script should exit gracefully rather than printing zero speeds.
Alternative Tools and Considerations
While bash scripting is excellent for learning and lightweight monitoring, production environments might benefit from dedicated tools. Utilities likenload, bmon, or vnstat provide graphical interfaces and historical data aggregation. However, these tools often rely on the same underlying kernel interfaces (/proc/net/dev or netlink sockets).
If you are building a dashboard, consider using jq to process JSON outputs from other APIs, or integrating this bash snippet into a larger monitoring stack like Prometheus via an exporter. Remember that high-frequency polling (e.g., every 100ms) can introduce CPU overhead. A one-second interval is usually sufficient for human-readable monitoring.
Frequently Asked Questions
Why is my network speed showing as zero?
This usually happens when the sampling interval is too short, resulting in no byte changes between reads. Increase the sleep duration to at least one second. Alternatively, ensure you are targeting an active interface with traffic.
Can I monitor Wi-Fi interfaces with this script?
Yes, provided the interface name is correct. Replace eth0 with your Wi-Fi interface name, such as wlan0 or wlp2s0. The /proc/net/dev interface remains consistent regardless of the physical medium.
Is it safe to expose ports used by monitoring scripts?
If your script opens a port to send data elsewhere, security becomes a concern. Exposing unnecessary ports increases attack surface. See Is it safe to expose a port opened from netcat? for best practices on securing network services.
How do I convert bits per second to megabits per second?
Divide the bits per second value by 1,000,000 for Mbps. In bash, you can use bc for floating-point math: echo "scale=2; $bps / 1000000" | bc.
Does this method work on macOS?
No, macOS does not have /proc/net/dev. On macOS, you would need to use ifconfig or netstat and parse their output, which has a different format. The column indices mentioned here are Linux-specific.