How to write current network speed

Abstract: Calculate real-time network speed in bits per second by parsing /proc/net/dev byte deltas without external dependencies.

Created: 2026-08-24 by
To write the current network speed using bash, you must parse /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 use eth0. 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 like nload, 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More