Created
June 7, 2024 07:40
-
-
Save naranyala/0b5c7d7a4cc0b9d53c5466bdb7b06091 to your computer and use it in GitHub Desktop.
smart selection and monitor your network-speed in polybar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Temporary file to store the selected interface | |
INTERFACE_FILE="/tmp/selected_network_interface" | |
# Default network interface | |
DEFAULT_INTERFACE="wlp2s0" | |
# Function to get available network interfaces | |
get_interfaces() { | |
ls /sys/class/net | grep -v lo | |
} | |
# Function to check internet connectivity | |
check_internet() { | |
ping -c 1 google.com > /dev/null 2>&1 | |
return $? | |
} | |
# Function to safely get network statistics | |
get_stat() { | |
local stat_file=$1 | |
if [ -f "$stat_file" ]; then | |
cat "$stat_file" | |
else | |
echo 0 | |
fi | |
} | |
# Function to monitor network speed | |
monitor_speed() { | |
INTERFACE=$1 | |
# Get initial download and upload bytes | |
RX1=$(get_stat "/sys/class/net/$INTERFACE/statistics/rx_bytes") | |
TX1=$(get_stat "/sys/class/net/$INTERFACE/statistics/tx_bytes") | |
# Wait for one second | |
sleep 1 | |
# Get new download and upload bytes | |
RX2=$(get_stat "/sys/class/net/$INTERFACE/statistics/rx_bytes") | |
TX2=$(get_stat "/sys/class/net/$INTERFACE/statistics/tx_bytes") | |
# Calculate bytes transferred in the interval | |
RXBPS=$(($RX2 - $RX1)) | |
TXBPS=$(($TX2 - $TX1)) | |
# Convert bytes per second to kilobytes per second | |
RXKBPS=$(echo "scale=2; $RXBPS/1024" | bc) | |
TXKBPS=$(echo "scale=2; $TXBPS/1024" | bc) | |
# Output the speeds | |
echo " $RXKBPS kB/s $TXKBPS kB/s" | |
} | |
# Function to select network interface | |
select_interface() { | |
INTERFACE=$(get_interfaces | rofi -dmenu -p "Select Network Interface:") | |
if [ -z "$INTERFACE" ]; then | |
echo "No interface selected" | |
exit 1 | |
fi | |
echo $INTERFACE > $INTERFACE_FILE | |
} | |
# Function to read interface from the temporary file | |
read_interface() { | |
if [ -f "$INTERFACE_FILE" ]; then | |
INTERFACE=$(cat $INTERFACE_FILE) | |
fi | |
if [ -z "$INTERFACE" ]; then | |
INTERFACE=$DEFAULT_INTERFACE | |
fi | |
} | |
# Main script | |
if [ "$1" == "monitor" ]; then | |
read_interface | |
monitor_speed $INTERFACE | |
elif [ "$1" == "select" ]; then | |
select_interface | |
else | |
echo "Usage: $0 [monitor|select]" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment